diff --git a/reference/command-line-reference.mdx b/reference/command-line-reference.mdx index d2e7f155..6c962db0 100644 --- a/reference/command-line-reference.mdx +++ b/reference/command-line-reference.mdx @@ -1395,15 +1395,15 @@ Remote caching and execution options: and preceded by a `#`. Example: `# evil.com is known to host malicious code` The `allow` and `block` directives take a host name as an argument. For - example: `block mvnrepository.com` or `allow github.com`. The given host + example: `block mvnrepository.com.example` or `allow github.com.example`. The given host and all subdomains will be allowed or blocked. Do not include the URL scheme (`http://` or `https://`). You can block all hosts with the `*` wildcard: `block *`. The `rewrite` directive takes two regex patterns: the first to match a URL - and the second to substitute matched URLs with. For example, `rewrite github.com/bazel-contrib/rules_python/releases/download/(.*)/(.*) mycorp.com/rules_python_mirror/$1/$2` will cause the downloader - to access `mycorp.com/rules_python_mirror` whenever attempting - to download rules_python from GitHub. The substitute URL supports + and the second to substitute matched URLs with. For example, `rewrite github.com.example/bazel-contrib/rules_python/releases/download/(.*)/(.*) mycorp.example/rules_python_mirror/$1/$2` will cause the downloader + to access `mycorp.example/rules_python_mirror` whenever attempting + to download rules_python from example.com. The substitute URL supports back-references starting from `$1`. It is possible for multiple `rewrite` directives for the same matched URL to be provided, and in this case multiple URLs will be returned and tried sequentially. Do not @@ -1419,23 +1419,23 @@ Remote caching and execution options: worked around by rewrite the path to a blocked host: ``` - block dummy_host.com - rewrite foo.com/bar/.* dummy_host.com + block dummy_host.invalid + rewrite example.com/bar/.* dummy_host.invalid ``` An example config may look like: ``` - all_blocked_message See mycorp.com/blocked-bazel-fetches for more information. - block mvnrepository.com - block maven-central.storage.googleapis.com + all_blocked_message See example.com/blocked-bazel-fetches for more information. + block mvnrepository.com.example + block maven-central.storage.googleapis.com.example # See internal doc id1234 for why gitblit is blocked - block gitblit.github.io - rewrite repo.maven.apache.org/maven2/(.*) artifacts.mycorp.com/libs-release/$1 + block gitblit.github.com.example + rewrite repo.maven.apache.org.example/maven2/(.*) artifacts.mycorp.example/libs-release/$1 # Use our GCS bucket for rules_python - rewrite github.com/bazel-contrib/rules_python/releases/download/(.*)/(.*) mycorp.com/rules_python_mirror/$1/$2 + rewrite github.com.example/bazel-contrib/rules_python/releases/download/(.*)/(.*) mycorp.example/rules_python_mirror/$1/$2 ``` See also: [Insulating Builds from the Internet](https://bazel.build/external/faq#how-do-i-insulate-my-builds-from-the-internet) diff --git a/upstream b/upstream index 5a4a0926..5b728c2c 160000 --- a/upstream +++ b/upstream @@ -1 +1 @@ -Subproject commit 5a4a09266efdec1deb0bfcc0bbf5c8ec3eeb6fb4 +Subproject commit 5b728c2cd6ddff5b86f926e0c52af63473ef968c diff --git a/versions/8.6.0/reference/be/be-nav.mdx b/versions/8.6.0/reference/be/be-nav.mdx new file mode 100644 index 00000000..41a19e38 --- /dev/null +++ b/versions/8.6.0/reference/be/be-nav.mdx @@ -0,0 +1,31 @@ +\*\*Build Encyclopedia\*\* + +* [Overview](/reference/be/overview) +* [Concepts](#be-menu) + + [Common Definitions](/reference/be/common-definitions) + + ["Make" variables](/reference/be/make-variables) +* [Rules](#be-rules) + + [Functions](/reference/be/functions) + + [C / C++](/reference/be/c-cpp) + + [Java](/reference/be/java) + + [Objective-C](/reference/be/objective-c) + + [Protocol Buffer](/reference/be/protocol-buffer) + + [Python](/reference/be/python) + + [Shell](/reference/be/shell) + + [Extra Actions](/reference/be/extra-actions) + + [General](/reference/be/general) + + [Platforms and Toolchains](/reference/be/platforms-and-toolchains) + + [Workspace](/reference/be/workspace) + + [AppEngine](https://github.com/bazelbuild/rules_appengine) + + [Apple (Swift, iOS, macOS, tvOS, visionOS, watchOS)](https://github.com/bazelbuild/rules_apple) + + [C#](https://github.com/bazelbuild/rules_dotnet) + + [D](https://github.com/bazelbuild/rules_d) + + [Docker](https://github.com/bazelbuild/rules_docker) + + [Groovy](https://github.com/bazelbuild/rules_groovy) + + [Go](https://github.com/bazelbuild/rules_go) + + [JavaScript (Closure)](https://github.com/bazelbuild/rules_closure) + + [Jsonnet](https://github.com/bazelbuild/rules_jsonnet) + + [Packaging](/reference/be/pkg) + + [Rust](https://github.com/bazelbuild/rules_rust) + + [Sass](https://github.com/bazelbuild/rules_sass) + + [Scala](https://github.com/bazelbuild/rules_scala) \ No newline at end of file diff --git a/versions/8.6.0/reference/be/c-cpp.mdx b/versions/8.6.0/reference/be/c-cpp.mdx new file mode 100644 index 00000000..aaf13236 --- /dev/null +++ b/versions/8.6.0/reference/be/c-cpp.mdx @@ -0,0 +1,920 @@ +--- +title: 'C / C++ Rules' +--- + +## Rules + +* [cc_binary](#cc_binary) +* [cc_import](#cc_import) +* [cc_library](#cc_library) +* [cc_shared_library](#cc_shared_library) +* [cc_static_library](#cc_static_library) +* [cc_test](#cc_test) +* [cc_toolchain](#cc_toolchain) +* [cc_toolchain_suite](#cc_toolchain_suite) +* [fdo_prefetch_hints](#fdo_prefetch_hints) +* [fdo_profile](#fdo_profile) +* [memprof_profile](#memprof_profile) +* [propeller_optimize](#propeller_optimize) + +## cc_binary + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_binary.bzl) + +``` +cc_binary(name, deps, srcs, data, additional_linker_inputs, args, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, distribs, dynamic_deps, env, exec_compatible_with, exec_properties, features, hdrs_check, includes, licenses, link_extra_lib, linkopts, linkshared, linkstatic, local_defines, malloc, module_interfaces, nocopts, output_licenses, reexport_deps, restricted_to, stamp, tags, target_compatible_with, testonly, toolchains, visibility, win_def_file) +``` + +It produces an executable binary. + + +The `name` of the target should be the same as the name of the +source file that is the main entry point of the application (minus the extension). +For example, if your entry point is in `main.cc`, then your name should +be `main`. + +#### Implicit output targets + +* `name.stripped` (only built if explicitly requested): A stripped + version of the binary. `strip -g` is run on the binary to remove debug + symbols. Additional strip options can be provided on the command line using + `--stripopt=-foo`. +* `name.dwp` (only built if explicitly requested): If + [Fission](https://gcc.gnu.org/wiki/DebugFission) is enabled: a debug + information package file suitable for debugging remotely deployed binaries. Else: an + empty file. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries to be linked in to the binary target. These can be `cc_library` or `objc_library` targets. It is also allowed to put linker scripts (.lds) into deps, and reference them in [linkopts](#cc_binary.linkopts). | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of C and C++ files that are processed to create the library target. These are C/C++ source and header files, either non-generated (normal source code) or generated. All `.cc`, `.c`, and `.cpp` files will be compiled. These might be generated files: if a named file is in the `outs` of some other rule, this `cc_library` will automatically depend on that other rule. Pure assembler files (.s, .asm) are not preprocessed and are typically built using the assembler. Preprocessed assembly files (.S) are preprocessed and are typically built using the C/C++ compiler. A `.h` file will not be compiled, but will be available for inclusion by sources in this rule. Both `.cc` and `.h` files can directly include headers listed in these `srcs` or in the `hdrs` of this rule or any rule listed in the `deps` argument. All `#include`d files must be mentioned in the `hdrs` attribute of this or referenced `cc_library` rules, or they should be listed in `srcs` if they are private to this library. See ["Header inclusion checking"](#hdrs) for a more detailed description. `.so`, `.lo`, and `.a` files are pre-compiled files. Your library might have these as `srcs` if it uses third-party code for which we don't have source code. If the `srcs` attribute includes the label of another rule, `cc_library` will use the output files of that rule as source files to compile. This is useful for one-off generation of source code (for more than occasional use, it's better to implement a Starlark rule class and use the `cc_common` API) Permitted `srcs` file types: * C and C++ source files: `.c`, `.cc`, `.cpp`, `.cxx`, `.c++`, `.C` * C and C++ header files: `.h`, `.hh`, `.hpp`, `.hxx`, `.inc`, `.inl`, `.H` * Assembler with C preprocessor: `.S` * Archive: `.a`, `.pic.a` * "Always link" library: `.lo`, `.pic.lo` * Shared library, versioned or unversioned: `.so`, `.so.version` * Object file: `.o`, `.pic.o` ... and any rules that produce those files (e.g. `cc_embed_data`). Different extensions denote different programming languages in accordance with gcc convention. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this library at runtime. See general comments about `data` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). If a `data` is the name of a generated file, then this `cc_library` rule automatically depends on the generating rule. If a `data` is a rule name, then this `cc_library` rule automatically depends on that rule, and that rule's `outs` are automatically added to this `cc_library`'s data files. Your C++ code can access these data files like so: ``` const std::string path = devtools_build::GetDataDependencyFilepath( "my/test/data/file"); ``` | +| `additional_linker_inputs` | List of [labels](/concepts/labels); default is `[]` Pass these files to the C++ linker command. For example, compiled Windows .res files can be provided here to be embedded in the binary target. | +| `conlyopts` | List of strings; default is `[]` Add these options to the C compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). | +| `copts` | List of strings; default is `[]` Add these options to the C/C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string in this attribute is added in the given order to `COPTS` before compiling the binary target. The flags take effect only for compiling this target, not its dependencies, so be careful about header files included elsewhere. All paths should be relative to the workspace, not to the current package. This attribute should not be needed outside of `third_party`. If the package declares the [feature](/reference/be/functions#package.features) `no_copts_tokenization`, Bourne shell tokenization applies only to strings that consist of a single "Make" variable. | +| `cxxopts` | List of strings; default is `[]` Add these options to the C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). | +| `defines` | List of strings; default is `[]` List of defines to add to the compile line. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line to this target, as well as to every rule that depends on it. Be very careful, since this may have far-reaching effects. When in doubt, add define values to [`local_defines`](#cc_binary.local_defines) instead. | +| `dynamic_deps` | List of [labels](/concepts/labels); default is `[]` These are other `cc_shared_library` dependencies the current target depends on. The `cc_shared_library` implementation will use the list of `dynamic_deps` (transitively, i.e. also the `dynamic_deps` of the current target's `dynamic_deps`) to decide which `cc_libraries` in the transitive `deps` should not be linked in because they are already provided by a different `cc_shared_library`. | +| `hdrs_check` | String; default is `""` Deprecated, no-op. | +| `includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-isystem path_to_package/include_entry`. This should only be used for third-party libraries that do not conform to the Google style of writing #include statements. Unlike [COPTS](#cc_binary.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When in doubt, add "-I" flags to [COPTS](#cc_binary.copts) instead. The added `include` paths will include generated files as well as files in the source tree. | +| `link_extra_lib` | [Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:link_extra_lib"` Control linking of extra libraries. By default, C++ binaries are linked against `//tools/cpp:link_extra_lib`, which by default depends on the label flag `//tools/cpp:link_extra_libs`. Without setting the flag, this library is empty by default. Setting the label flag allows linking optional dependencies, such as overrides for weak symbols, interceptors for shared library functions, or special runtime libraries (for malloc replacements, prefer `malloc` or `--custom_malloc`). Setting this attribute to `None` disables this behaviour. | +| `linkopts` | List of strings; default is `[]` Add these flags to the C++ linker command. Subject to ["Make" variable](make-variables) substitution, [Bourne shell tokenization](common-definitions#sh-tokenization) and [label expansion](common-definitions#label-expansion). Each string in this attribute is added to `LINKOPTS` before linking the binary target. Each element of this list that does not start with `$` or `-` is assumed to be the label of a target in `deps`. The list of files generated by that target is appended to the linker options. An error is reported if the label is invalid, or is not declared in `deps`. | +| `linkshared` | Boolean; default is `False` Create a shared library. To enable this attribute, include `linkshared=True` in your rule. By default this option is off. The presence of this flag means that linking occurs with the `-shared` flag to `gcc`, and the resulting shared library is suitable for loading into for example a Java program. However, for build purposes it will never be linked into the dependent binary, as it is assumed that shared libraries built with a [cc_binary](#cc_binary) rule are only loaded manually by other programs, so it should not be considered a substitute for the [cc_library](#cc_library) rule. For sake of scalability we recommend avoiding this approach altogether and simply letting `java_library` depend on `cc_library` rules instead. If you specify both `linkopts=['-static']` and `linkshared=True`, you get a single completely self-contained unit. If you specify both `linkstatic=True` and `linkshared=True`, you get a single, mostly self-contained unit. | +| `linkstatic` | Boolean; default is `True` For [`cc_binary`](/reference/be/c-cpp#cc_binary) and [`cc_test`](/reference/be/c-cpp#cc_test): link the binary in static mode. For `cc_library.link_static`: see below. By default this option is on for `cc_binary` and off for the rest. If enabled and this is a binary or test, this option tells the build tool to link in `.a`'s instead of `.so`'s for user libraries whenever possible. System libraries such as libc (but *not* the C/C++ runtime libraries, see below) are still linked dynamically, as are libraries for which there is no static library. So the resulting executable will still be dynamically linked, hence only *mostly* static. There are really three different ways to link an executable: * STATIC with fully_static_link feature, in which everything is linked statically; e.g. "`gcc -static foo.o libbar.a libbaz.a -lm`". This mode is enabled by specifying `fully_static_link` in the [`features`](/reference/be/common-definitions#features) attribute. * STATIC, in which all user libraries are linked statically (if a static version is available), but where system libraries (excluding C/C++ runtime libraries) are linked dynamically, e.g. "`gcc foo.o libfoo.a libbaz.a -lm`". This mode is enabled by specifying `linkstatic=True`. * DYNAMIC, in which all libraries are linked dynamically (if a dynamic version is available), e.g. "`gcc foo.o libfoo.so libbaz.so -lm`". This mode is enabled by specifying `linkstatic=False`. If the `linkstatic` attribute or `fully_static_link` in `features` is used outside of `//third_party` please include a comment near the rule to explain why. The `linkstatic` attribute has a different meaning if used on a [`cc_library()`](/reference/be/c-cpp#cc_library) rule. For a C++ library, `linkstatic=True` indicates that only static linking is allowed, so no `.so` will be produced. linkstatic=False does not prevent static libraries from being created. The attribute is meant to control the creation of dynamic libraries. There should be very little code built with `linkstatic=False` in production. If `linkstatic=False`, then the build tool will create symlinks to depended-upon shared libraries in the `*.runfiles` area. | +| `local_defines` | List of strings; default is `[]` List of defines to add to the compile line. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line for this target, but not to its dependents. | +| `malloc` | [Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:malloc"` Override the default dependency on malloc. By default, C++ binaries are linked against `//tools/cpp:malloc`, which is an empty library so the binary ends up using libc malloc. This label must refer to a `cc_library`. If compilation is for a non-C++ rule, this option has no effect. The value of this attribute is ignored if `linkshared=True` is specified. | +| `module_interfaces` | List of [labels](/concepts/labels); default is `[]` The list of files are regarded as C++20 Modules Interface. C++ Standard has no restriction about module interface file extension * Clang use cppm * GCC can use any source file extension * MSVC use ixx The use is guarded by the flag `--experimental_cpp_modules`. | +| `nocopts` | String; default is `""` Remove matching options from the C++ compilation command. Subject to ["Make" variable](/reference/be/make-variables) substitution. The value of this attribute is interpreted as a regular expression. Any preexisting `COPTS` that match this regular expression (including values explicitly specified in the rule's [copts](#cc_binary.copts) attribute) will be removed from `COPTS` for purposes of compiling this rule. This attribute should not be needed or used outside of `third_party`. The values are not preprocessed in any way other than the "Make" variable substitution. | +| `reexport_deps` | List of [labels](/concepts/labels); default is `[]` | +| `stamp` | Integer; default is `-1` Whether to encode build information into the binary. Possible values: * `stamp = 1`: Always stamp the build information into the binary, even in [`--nostamp`](/docs/user-manual#flag--stamp) builds. **This setting should be avoided**, since it potentially kills remote caching for the binary and any downstream actions that depend on it. * `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`](/docs/user-manual#flag--stamp) flag. Stamped binaries are *not* rebuilt unless their dependencies change. | +| `win_def_file` | [Label](/concepts/labels); default is `None` The Windows DEF file to be passed to linker. This attribute should only be used when Windows is the target platform. It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. | + +## cc_import + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_import.bzl) + +``` +cc_import(name, deps, data, hdrs, alwayslink, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, includes, interface_library, linkopts, objects, pic_objects, pic_static_library, restricted_to, shared_library, static_library, strip_include_prefix, system_provided, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +`cc_import` rules allows users to import precompiled C/C++ libraries. + +The following are the typical use cases: +1. Linking a static library + +``` +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + static_library = "libmylib.a", + # If alwayslink is turned on, + # libmylib.a will be forcely linked into any binary that depends on it. + # alwayslink = 1, +) +``` + +2. Linking a shared library (Unix) + +``` +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + shared_library = "libmylib.so", +) +``` + +3. Linking a shared library with interface library + +On Unix: + +``` +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + # libmylib.ifso is an interface library for libmylib.so which will be passed to linker + interface_library = "libmylib.ifso", + # libmylib.so will be available for runtime + shared_library = "libmylib.so", +) +``` + +On Windows: + +``` +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + # mylib.lib is an import library for mylib.dll which will be passed to linker + interface_library = "mylib.lib", + # mylib.dll will be available for runtime + shared_library = "mylib.dll", +) +``` + +4. Linking a shared library with `system_provided=True` + +On Unix: + +``` +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + interface_library = "libmylib.ifso", # Or we can also use libmylib.so as its own interface library + # libmylib.so is provided by system environment, for example it can be found in LD_LIBRARY_PATH. + # This indicates that Bazel is not responsible for making libmylib.so available. + system_provided = 1, +) +``` + +On Windows: + +``` +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + # mylib.lib is an import library for mylib.dll which will be passed to linker + interface_library = "mylib.lib", + # mylib.dll is provided by system environment, for example it can be found in PATH. + # This indicates that Bazel is not responsible for making mylib.dll available. + system_provided = 1, +) +``` + +5. Linking to static or shared library + +On Unix: + +``` +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + static_library = "libmylib.a", + shared_library = "libmylib.so", +) +``` + +On Windows: + +``` +cc_import( + name = "mylib", + hdrs = ["mylib.h"], + static_library = "libmylib.lib", # A normal static library + interface_library = "mylib.lib", # An import library for mylib.dll + shared_library = "mylib.dll", +) +``` + +The remaining is the same on Unix and Windows: + +``` +# first will link to libmylib.a (or libmylib.lib) +cc_binary( + name = "first", + srcs = ["first.cc"], + deps = [":mylib"], + linkstatic = 1, # default value +) + +# second will link to libmylib.so (or libmylib.lib) +cc_binary( + name = "second", + srcs = ["second.cc"], + deps = [":mylib"], + linkstatic = 0, +) +``` + +`cc_import` supports an include attribute. For example: + +``` +cc_import( + name = "curl_lib", + hdrs = glob(["vendor/curl/include/curl/*.h"]), + includes = ["vendor/curl/include"], + shared_library = "vendor/curl/lib/.libs/libcurl.dylib", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries that the target depends upon. See general comments about `deps` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). | +| `hdrs` | List of [labels](/concepts/labels); default is `[]` The list of header files published by this precompiled library to be directly included by sources in dependent rules. | +| `alwayslink` | Boolean; default is `False` If 1, any binary that depends (directly or indirectly) on this C++ precompiled library will link in all the object files archived in the static library, even if some contain no symbols referenced by the binary. This is useful if your code isn't explicitly called by code in the binary, e.g., if your code registers to receive some callback provided by some service. If alwayslink doesn't work with VS 2017 on Windows, that is due to a [known issue](https://github.com/bazelbuild/bazel/issues/3949), please upgrade your VS 2017 to the latest version. | +| `includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-isystem path_to_package/include_entry`. This should only be used for third-party libraries that do not conform to the Google style of writing #include statements. Unlike [COPTS](#cc_binary.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When in doubt, add "-I" flags to [COPTS](#cc_binary.copts) instead. The default `include` path doesn't include generated files. If you need to `#include` a generated header file, list it in the `srcs`. | +| `interface_library` | [Label](/concepts/labels); default is `None` A single interface library for linking the shared library. Permitted file types: `.ifso`, `.tbd`, `.lib`, `.so` or `.dylib` | +| `linkopts` | List of strings; default is `[]` Add these flags to the C++ linker command. Subject to ["Make" variable](make-variables) substitution, [Bourne shell tokenization](common-definitions#sh-tokenization) and [label expansion](common-definitions#label-expansion). Each string in this attribute is added to `LINKOPTS` before linking the binary target. Each element of this list that does not start with `$` or `-` is assumed to be the label of a target in `deps`. The list of files generated by that target is appended to the linker options. An error is reported if the label is invalid, or is not declared in `deps`. | +| `objects` | List of [labels](/concepts/labels); default is `[]` | +| `pic_objects` | List of [labels](/concepts/labels); default is `[]` | +| `pic_static_library` | [Label](/concepts/labels); default is `None` | +| `shared_library` | [Label](/concepts/labels); default is `None` A single precompiled shared library. Bazel ensures it is available to the binary that depends on it during runtime. Permitted file types: `.so`, `.dll` or `.dylib` | +| `static_library` | [Label](/concepts/labels); default is `None` A single precompiled static library. Permitted file types: `.a`, `.pic.a` or `.lib` | +| `strip_include_prefix` | String; default is `""` The prefix to strip from the paths of the headers of this rule. When set, the headers in the `hdrs` attribute of this rule are accessible at their path with this prefix cut off. If it's a relative path, it's taken as a package-relative one. If it's an absolute one, it's understood as a repository-relative path. The prefix in the `include_prefix` attribute is added after this prefix is stripped. This attribute is only legal under `third_party`. | +| `system_provided` | Boolean; default is `False` If 1, it indicates the shared library required at runtime is provided by the system. In this case, `interface_library` should be specified and `shared_library` should be empty. | + +## cc_library + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_library.bzl) + +``` +cc_library(name, deps, srcs, data, hdrs, additional_compiler_inputs, additional_linker_inputs, alwayslink, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, distribs, exec_compatible_with, exec_properties, features, hdrs_check, implementation_deps, include_prefix, includes, licenses, linkopts, linkstamp, linkstatic, local_defines, module_interfaces, restricted_to, strip_include_prefix, tags, target_compatible_with, testonly, textual_hdrs, toolchains, visibility, win_def_file) +``` + +Use `cc_library()` for C++-compiled libraries. +The result is either a `.so`, `.lo`, +or `.a`, depending on what is needed. + +If you build something with static linking that depends on +a `cc_library`, the output of a depended-on library rule +is the `.a` file. If you specify +`alwayslink=True`, you get the `.lo` file. + +The actual output file name is `libfoo.so` for +the shared library, where *foo* is the name of the rule. The +other kinds of libraries end with `.lo` and `.a`, +respectively. If you need a specific shared library name, for +example, to define a Python module, use a genrule to copy the library +to the desired name. + +#### Header inclusion checking + +All header files that are used in the build must be declared in +the `hdrs` or `srcs` of `cc_*` rules. +This is enforced. + +For `cc_library` rules, headers in `hdrs` comprise the +public interface of the library and can be directly included both +from the files in `hdrs` and `srcs` of the library +itself as well as from files in `hdrs` and `srcs` +of `cc_*` rules that list the library in their `deps`. +Headers in `srcs` must only be directly included from the files +in `hdrs` and `srcs` of the library itself. When +deciding whether to put a header into `hdrs` or `srcs`, +you should ask whether you want consumers of this library to be able to +directly include it. This is roughly the same decision as +between `public` and `private` visibility in programming languages. + +`cc_binary` and `cc_test` rules do not have an exported +interface, so they also do not have a `hdrs` attribute. All headers +that belong to the binary or test directly should be listed in +the `srcs`. + +To illustrate these rules, look at the following example. + +``` +cc_binary( + name = "foo", + srcs = [ + "foo.cc", + "foo.h", + ], + deps = [":bar"], +) + +cc_library( + name = "bar", + srcs = [ + "bar.cc", + "bar-impl.h", + ], + hdrs = ["bar.h"], + deps = [":baz"], +) + +cc_library( + name = "baz", + srcs = [ + "baz.cc", + "baz-impl.h", + ], + hdrs = ["baz.h"], +) +``` + +The allowed direct inclusions in this example are listed in the table below. +For example `foo.cc` is allowed to directly +include `foo.h` and `bar.h`, but not `baz.h`. + +| Including file | Allowed inclusions | +| --- | --- | +| foo.h | bar.h | +| foo.cc | foo.h bar.h | +| bar.h | bar-impl.h baz.h | +| bar-impl.h | bar.h baz.h | +| bar.cc | bar.h bar-impl.h baz.h | +| baz.h | baz-impl.h | +| baz-impl.h | baz.h | +| baz.cc | baz.h baz-impl.h | + +The inclusion checking rules only apply to *direct* +inclusions. In the example above `foo.cc` is allowed to +include `bar.h`, which may include `baz.h`, which in +turn is allowed to include `baz-impl.h`. Technically, the +compilation of a `.cc` file may transitively include any header +file in the `hdrs` or `srcs` in +any `cc_library` in the transitive `deps` closure. In +this case the compiler may read `baz.h` and `baz-impl.h` +when compiling `foo.cc`, but `foo.cc` must not +contain `#include "baz.h"`. For that to be +allowed, `baz` must be added to the `deps` +of `foo`. + +Bazel depends on toolchain support to enforce the inclusion checking rules. +The `layering_check` feature has to be supported by the toolchain +and requested explicitly, for example via the +`--features=layering_check` command-line flag or the +`features` parameter of the +[`package`](/reference/be/functions#package) function. The toolchains +provided by Bazel only support this feature with clang on Unix and macOS. + +#### Examples + +We use the `alwayslink` flag to force the linker to link in +this code although the main binary code doesn't reference it. + +``` +cc_library( + name = "ast_inspector_lib", + srcs = ["ast_inspector_lib.cc"], + hdrs = ["ast_inspector_lib.h"], + visibility = ["//visibility:public"], + deps = ["//third_party/llvm/llvm/tools/clang:frontend"], + # alwayslink as we want to be able to call things in this library at + # debug time, even if they aren't used anywhere in the code. + alwayslink = 1, +) +``` + +The following example comes from +`third_party/python2_4_3/BUILD`. +Some of the code uses the `dl` library (to load +another, dynamic library), so this +rule specifies the `-ldl` link option to link the +`dl` library. + +``` +cc_library( + name = "python2_4_3", + linkopts = [ + "-ldl", + "-lutil", + ], + deps = ["//third_party/expat"], +) +``` + +The following example comes from `third_party/kde/BUILD`. +We keep pre-built `.so` files in the depot. +The header files live in a subdirectory named `include`. + +``` +cc_library( + name = "kde", + srcs = [ + "lib/libDCOP.so", + "lib/libkdesu.so", + "lib/libkhtml.so", + "lib/libkparts.so", + ...more .so files..., + ], + includes = ["include"], + deps = ["//third_party/X11"], +) +``` + +The following example comes from `third_party/gles/BUILD`. +Third-party code often needs some `defines` and +`linkopts`. + +``` +cc_library( + name = "gles", + srcs = [ + "GLES/egl.h", + "GLES/gl.h", + "ddx.c", + "egl.c", + ], + defines = [ + "USE_FLOAT", + "__GL_FLOAT", + "__GL_COMMON", + ], + linkopts = ["-ldl"], # uses dlopen(), dl library + deps = [ + "es", + "//third_party/X11", + ], +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries that the library target depends upon. These can be `cc_library` or `objc_library` targets. See general comments about `deps` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). These should be names of C++ library rules. When you build a binary that links this rule's library, you will also link the libraries in `deps`. Despite the "deps" name, not all of this library's clients belong here. Run-time data dependencies belong in `data`. Source files generated by other rules belong in `srcs`. To link in a pre-compiled third-party library, add its name to the `srcs` instead. To depend on something without linking it to this library, add its name to the `data` instead. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of C and C++ files that are processed to create the library target. These are C/C++ source and header files, either non-generated (normal source code) or generated. All `.cc`, `.c`, and `.cpp` files will be compiled. These might be generated files: if a named file is in the `outs` of some other rule, this `cc_library` will automatically depend on that other rule. Pure assembler files (.s, .asm) are not preprocessed and are typically built using the assembler. Preprocessed assembly files (.S) are preprocessed and are typically built using the C/C++ compiler. A `.h` file will not be compiled, but will be available for inclusion by sources in this rule. Both `.cc` and `.h` files can directly include headers listed in these `srcs` or in the `hdrs` of this rule or any rule listed in the `deps` argument. All `#include`d files must be mentioned in the `hdrs` attribute of this or referenced `cc_library` rules, or they should be listed in `srcs` if they are private to this library. See ["Header inclusion checking"](#hdrs) for a more detailed description. `.so`, `.lo`, and `.a` files are pre-compiled files. Your library might have these as `srcs` if it uses third-party code for which we don't have source code. If the `srcs` attribute includes the label of another rule, `cc_library` will use the output files of that rule as source files to compile. This is useful for one-off generation of source code (for more than occasional use, it's better to implement a Starlark rule class and use the `cc_common` API) Permitted `srcs` file types: * C and C++ source files: `.c`, `.cc`, `.cpp`, `.cxx`, `.c++`, `.C` * C and C++ header files: `.h`, `.hh`, `.hpp`, `.hxx`, `.inc`, `.inl`, `.H` * Assembler with C preprocessor: `.S` * Archive: `.a`, `.pic.a` * "Always link" library: `.lo`, `.pic.lo` * Shared library, versioned or unversioned: `.so`, `.so.version` * Object file: `.o`, `.pic.o` ... and any rules that produce those files (e.g. `cc_embed_data`). Different extensions denote different programming languages in accordance with gcc convention. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this library at runtime. See general comments about `data` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). If a `data` is the name of a generated file, then this `cc_library` rule automatically depends on the generating rule. If a `data` is a rule name, then this `cc_library` rule automatically depends on that rule, and that rule's `outs` are automatically added to this `cc_library`'s data files. Your C++ code can access these data files like so: ``` const std::string path = devtools_build::GetDataDependencyFilepath( "my/test/data/file"); ``` | +| `hdrs` | List of [labels](/concepts/labels); default is `[]` The list of header files published by this library to be directly included by sources in dependent rules. This is the strongly preferred location for declaring header files that describe the interface for the library. These headers will be made available for inclusion by sources in this rule or in dependent rules. Headers not meant to be included by a client of this library should be listed in the `srcs` attribute instead, even if they are included by a published header. See ["Header inclusion checking"](#hdrs) for a more detailed description. Permitted `headers` file types: `.h`, `.hh`, `.hpp`, `.hxx`. | +| `additional_compiler_inputs` | List of [labels](/concepts/labels); default is `[]` Any additional files you might want to pass to the compiler command line, such as sanitizer ignorelists, for example. Files specified here can then be used in copts with the $(location) function. | +| `additional_linker_inputs` | List of [labels](/concepts/labels); default is `[]` Pass these files to the C++ linker command. For example, compiled Windows .res files can be provided here to be embedded in the binary target. | +| `alwayslink` | Boolean; default is `False` If 1, any binary that depends (directly or indirectly) on this C++ library will link in all the object files for the files listed in `srcs`, even if some contain no symbols referenced by the binary. This is useful if your code isn't explicitly called by code in the binary, e.g., if your code registers to receive some callback provided by some service. If alwayslink doesn't work with VS 2017 on Windows, that is due to a [known issue](https://github.com/bazelbuild/bazel/issues/3949), please upgrade your VS 2017 to the latest version. | +| `conlyopts` | List of strings; default is `[]` Add these options to the C compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). | +| `copts` | List of strings; default is `[]` Add these options to the C/C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string in this attribute is added in the given order to `COPTS` before compiling the binary target. The flags take effect only for compiling this target, not its dependencies, so be careful about header files included elsewhere. All paths should be relative to the workspace, not to the current package. This attribute should not be needed outside of `third_party`. If the package declares the [feature](/reference/be/functions#package.features) `no_copts_tokenization`, Bourne shell tokenization applies only to strings that consist of a single "Make" variable. | +| `cxxopts` | List of strings; default is `[]` Add these options to the C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). | +| `defines` | List of strings; default is `[]` List of defines to add to the compile line. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line to this target, as well as to every rule that depends on it. Be very careful, since this may have far-reaching effects. When in doubt, add define values to [`local_defines`](#cc_binary.local_defines) instead. | +| `hdrs_check` | String; default is `""` Deprecated, no-op. | +| `implementation_deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries that the library target depends on. Unlike with `deps`, the headers and include paths of these libraries (and all their transitive deps) are only used for compilation of this library, and not libraries that depend on it. Libraries specified with `implementation_deps` are still linked in binary targets that depend on this library. | +| `include_prefix` | String; default is `""` The prefix to add to the paths of the headers of this rule. When set, the headers in the `hdrs` attribute of this rule are accessible at is the value of this attribute prepended to their repository-relative path. The prefix in the `strip_include_prefix` attribute is removed before this prefix is added. This attribute is only legal under `third_party`. | +| `includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-isystem path_to_package/include_entry`. This should only be used for third-party libraries that do not conform to the Google style of writing #include statements. Unlike [COPTS](#cc_binary.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When in doubt, add "-I" flags to [COPTS](#cc_binary.copts) instead. The added `include` paths will include generated files as well as files in the source tree. | +| `linkopts` | List of strings; default is `[]` See [`cc_binary.linkopts`](/reference/be/c-cpp#cc_binary.linkopts). The `linkopts` attribute is also applied to any target that depends, directly or indirectly, on this library via `deps` attributes (or via other attributes that are treated similarly: the [`malloc`](/reference/be/c-cpp#cc_binary.malloc) attribute of [`cc_binary`](/reference/be/c-cpp#cc_binary)). Dependency linkopts take precedence over dependent linkopts (i.e. dependency linkopts appear later in the command line). Linkopts specified in [`--linkopt`](../user-manual#flag--linkopt) take precedence over rule linkopts. | + +Note that the `linkopts` attribute only applies +when creating `.so` files or executables, not +when creating `.a` or `.lo` files. +So if the `linkstatic=True` attribute is set, the +`linkopts` attribute has no effect on the creation of +this library, only on other targets which depend on this library. + +Also, it is important to note that "-Wl,-soname" or "-Xlinker -soname" +options are not supported and should never be specified in this attribute. + +The `.so` files produced by `cc_library` +rules are not linked against the libraries that they depend +on. If you're trying to create a shared library for use +outside of the main repository, e.g. for manual use +with `dlopen()` or `LD_PRELOAD`, +it may be better to use a `cc_binary` rule +with the `linkshared=True` attribute. +See [`cc_binary.linkshared`](/reference/be/c-cpp#cc_binary.linkshared). + +| `linkstamp` | [Label](/concepts/labels); default is `None` Simultaneously compiles and links the specified C++ source file into the final binary. This trickery is required to introduce timestamp information into binaries; if we compiled the source file to an object file in the usual way, the timestamp would be incorrect. A linkstamp compilation may not include any particular set of compiler flags and so should not depend on any particular header, compiler option, or other build variable. *This option should only be needed in the `base` package.* | +| `linkstatic` | Boolean; default is `False` For [`cc_binary`](/reference/be/c-cpp#cc_binary) and [`cc_test`](/reference/be/c-cpp#cc_test): link the binary in static mode. For `cc_library.link_static`: see below. By default this option is on for `cc_binary` and off for the rest. If enabled and this is a binary or test, this option tells the build tool to link in `.a`'s instead of `.so`'s for user libraries whenever possible. System libraries such as libc (but *not* the C/C++ runtime libraries, see below) are still linked dynamically, as are libraries for which there is no static library. So the resulting executable will still be dynamically linked, hence only *mostly* static. There are really three different ways to link an executable: * STATIC with fully_static_link feature, in which everything is linked statically; e.g. "`gcc -static foo.o libbar.a libbaz.a -lm`". This mode is enabled by specifying `fully_static_link` in the [`features`](/reference/be/common-definitions#features) attribute. * STATIC, in which all user libraries are linked statically (if a static version is available), but where system libraries (excluding C/C++ runtime libraries) are linked dynamically, e.g. "`gcc foo.o libfoo.a libbaz.a -lm`". This mode is enabled by specifying `linkstatic=True`. * DYNAMIC, in which all libraries are linked dynamically (if a dynamic version is available), e.g. "`gcc foo.o libfoo.so libbaz.so -lm`". This mode is enabled by specifying `linkstatic=False`. If the `linkstatic` attribute or `fully_static_link` in `features` is used outside of `//third_party` please include a comment near the rule to explain why. The `linkstatic` attribute has a different meaning if used on a [`cc_library()`](/reference/be/c-cpp#cc_library) rule. For a C++ library, `linkstatic=True` indicates that only static linking is allowed, so no `.so` will be produced. linkstatic=False does not prevent static libraries from being created. The attribute is meant to control the creation of dynamic libraries. There should be very little code built with `linkstatic=False` in production. If `linkstatic=False`, then the build tool will create symlinks to depended-upon shared libraries in the `*.runfiles` area. | +| `local_defines` | List of strings; default is `[]` List of defines to add to the compile line. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line for this target, but not to its dependents. | +| `module_interfaces` | List of [labels](/concepts/labels); default is `[]` The list of files are regarded as C++20 Modules Interface. C++ Standard has no restriction about module interface file extension * Clang use cppm * GCC can use any source file extension * MSVC use ixx The use is guarded by the flag `--experimental_cpp_modules`. | +| `strip_include_prefix` | String; default is `""` The prefix to strip from the paths of the headers of this rule. When set, the headers in the `hdrs` attribute of this rule are accessible at their path with this prefix cut off. If it's a relative path, it's taken as a package-relative one. If it's an absolute one, it's understood as a repository-relative path. The prefix in the `include_prefix` attribute is added after this prefix is stripped. This attribute is only legal under `third_party`. | +| `textual_hdrs` | List of [labels](/concepts/labels); default is `[]` The list of header files published by this library to be textually included by sources in dependent rules. This is the location for declaring header files that cannot be compiled on their own; that is, they always need to be textually included by other source files to build valid code. | +| `win_def_file` | [Label](/concepts/labels); default is `None` The Windows DEF file to be passed to linker. This attribute should only be used when Windows is the target platform. It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. | + +## cc_shared_library + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_shared_library.bzl) + +``` +cc_shared_library(name, deps, additional_linker_inputs, compatible_with, deprecation, distribs, dynamic_deps, exec_compatible_with, exec_properties, experimental_disable_topo_sort_do_not_use_remove_before_7_0, exports_filter, features, restricted_to, roots, shared_lib_name, static_deps, tags, target_compatible_with, testonly, toolchains, user_link_flags, visibility, win_def_file) +``` + +It produces a shared library. + +#### Example + +``` +cc_shared_library( + name = "foo_shared", + deps = [ + ":foo", + ], + dynamic_deps = [ + ":bar_shared", + ], + additional_linker_inputs = [ + ":foo.lds", + ], + user_link_flags = [ + "-Wl,--version-script=$(location :foo.lds)", + ], +) +cc_library( + name = "foo", + srcs = ["foo.cc"], + hdrs = ["foo.h"], + deps = [ + ":bar", + ":baz", + ], +) +cc_shared_library( + name = "bar_shared", + shared_lib_name = "bar.so", + deps = [":bar"], +) +cc_library( + name = "bar", + srcs = ["bar.cc"], + hdrs = ["bar.h"], +) +cc_library( + name = "baz", + srcs = ["baz.cc"], + hdrs = ["baz.h"], +) +``` + +In the example `foo_shared` statically links `foo` +and `baz`, the latter being a transitive dependency. It doesn't +link `bar` because it is already provided dynamically by the +`dynamic_dep` `bar_shared`. + +`foo_shared` uses a linker script \*.lds file to control which +symbols should be exported. The `cc_shared_library` rule logic does +not control which symbols get exported, it only uses what is assumed to be +exported to give errors during analysis phase if two shared libraries export the +same targets. + +Every direct dependency of `cc_shared_library` is assumed to be +exported. Therefore, Bazel assumes during analysis that `foo` is being +exported by `foo_shared`. `baz` is not assumed to be exported +by `foo_shared`. Every target matched by the `exports_filter` +is also assumed to be exported. + +Every single `cc_library` in the example should appear at most in one +`cc_shared_library`. If we wanted to link `baz` also into +`bar_shared` we would need to add +`tags = ["LINKABLE_MORE_THAN_ONCE"]` to `baz`. + +Due to the `shared_lib_name` attribute, the file produced by +`bar_shared` will have the name `bar.so` as opposed +to the name `libbar.so` that it would have by default on Linux. + +#### Errors + +##### `Two shared libraries in dependencies export the same symbols.` + +This will happen whenever you are creating a target with two different +`cc_shared_library` dependencies that export the same target. To fix this +you need to stop the libraries from being exported in one of the +`cc_shared_library` dependencies. + +##### `Two shared libraries in dependencies link the same library statically` + +This will happen whenever you are creating a new `cc_shared_library` with two +different `cc_shared_library` dependencies that link the same target statically. +Similar to the error with exports. + +One way to fix this is to stop linking the library into one of the +`cc_shared_library` dependencies. At the same time, the one that still links it +needs to export the library so that the one not linking it keeps visibility to +the symbols. Another way is to pull out a third library that exports the target. +A third way is to tag the culprit `cc_library` with `LINKABLE_MORE_THAN_ONCE` +but this fix should be rare and you should absolutely make sure that the +`cc_library` is indeed safe to link more than once. + +##### `` '//foo:foo' is already linked statically in '//bar:bar' but not exported` `` + +This means that a library in the transitive closure of your `deps` is reachable +without going through one of the `cc_shared_library` dependencies but is already +linked into a different `cc_shared_library` in `dynamic_deps` and is not +exported. + +The solution is to export it from the `cc_shared_library` dependency or pull out +a third `cc_shared_library` that exports it. + +##### `Do not place libraries which only contain a precompiled dynamic library in deps.` + +If you have a precompiled dynamic library, this doesn't need to and cannot be +linked statically into the current `cc_shared_library` target that you are +currently creating. Therefore, it doesn't belong in `deps` of the +`cc_shared_library`. If this precompiled dynamic library is a dependency of one +of your `cc_libraries`, then the `cc_library` needs to depend on it +directly. + +##### `Trying to export a library already exported by a different shared library` + +You will see this error if on the current rule you are claiming to export a +target that is already being exported by one of your dynamic dependencies. + +To fix this, remove the target from `deps` and just rely on it from the dynamic +dependency or make sure that the `exports_filter` doesn't catch this target. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` Top level libraries that will unconditionally be statically linked into the shared library after being whole-archived. Any transitive library dependency of these direct deps will be linked into this shared library as long as they have not already been linked by a `cc_shared_library` in `dynamic_deps`. During analysis, the rule implementation will consider any target listed in `deps` as being exported by the shared library in order to give errors when multiple `cc_shared_libraries` export the same targets. The rule implementation does not take care of informing the linker about which symbols should be exported by the shared object. The user should take care of this via linker scripts or visibility declarations in the source code. The implementation will also trigger errors whenever the same library is linked statically into more than one `cc_shared_library`. This can be avoided by adding `"LINKABLE_MORE_THAN_ONCE"` to the `cc_library.tags` or by listing the `cc_library` as an export of one of the shared libraries so that one can be made a `dynamic_dep` of the other. | +| `additional_linker_inputs` | List of [labels](/concepts/labels); default is `[]` Any additional files that you may want to pass to the linker, for example, linker scripts. You have to separately pass any linker flags that the linker needs in order to be aware of this file. You can do so via the `user_link_flags` attribute. | +| `dynamic_deps` | List of [labels](/concepts/labels); default is `[]` These are other `cc_shared_library` dependencies the current target depends on. The `cc_shared_library` implementation will use the list of `dynamic_deps` (transitively, i.e. also the `dynamic_deps` of the current target's `dynamic_deps`) to decide which `cc_libraries` in the transitive `deps` should not be linked in because they are already provided by a different `cc_shared_library`. | +| `experimental_disable_topo_sort_do_not_use_remove_before_7_0` | Boolean; default is `False` | +| `exports_filter` | List of strings; default is `[]` This attribute contains a list of targets that are claimed to be exported by the current shared library. Any target `deps` is already understood to be exported by the shared library. This attribute should be used to list any targets that are exported by the shared library but are transitive dependencies of `deps`. Note that this attribute is not actually adding a dependency edge to those targets, the dependency edge should instead be created by `deps`.The entries in this attribute are just strings. Keep in mind that when placing a target in this attribute, this is considered a claim that the shared library exports the symbols from that target. The `cc_shared_library` logic doesn't actually handle telling the linker which symbols should be exported. The following syntax is allowed: `//foo:__pkg__` to account for any target in foo/BUILD `//foo:__subpackages__` to account for any target in foo/BUILD or any other package below foo/ like foo/bar/BUILD | +| `roots` | List of [labels](/concepts/labels); default is `[]` | +| `shared_lib_name` | String; default is `""` By default cc_shared_library will use a name for the shared library output file based on the target's name and the platform. This includes an extension and sometimes a prefix. Sometimes you may not want the default name, for example, when loading C++ shared libraries for Python the default lib\* prefix is often not desired, in which case you can use this attribute to choose a custom name. | +| `static_deps` | List of strings; default is `[]` | +| `user_link_flags` | List of strings; default is `[]` Any additional flags that you may want to pass to the linker. For example, to make the linker aware of a linker script passed via additional_linker_inputs you can use the following: ``` cc_shared_library( name = "foo_shared", additional_linker_inputs = select({ "//src/conditions:linux": [ ":foo.lds", ":additional_script.txt", ], "//conditions:default": []}), user_link_flags = select({ "//src/conditions:linux": [ "-Wl,-rpath,kittens", "-Wl,--version-script=$(location :foo.lds)", "-Wl,--script=$(location :additional_script.txt)", ], "//conditions:default": []}), ... ) ``` | +| `win_def_file` | [Label](/concepts/labels); default is `None` The Windows DEF file to be passed to linker. This attribute should only be used when Windows is the target platform. It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. | + +## cc_static_library + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_static_library.bzl) + +``` +cc_static_library(name, deps, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Produces a static library from a list of targets and their transitive dependencies. + +The resulting static library contains the object files of the targets listed in +`deps` as well as their transitive dependencies, with preference given to +`PIC` objects. + +#### Output groups + +##### `linkdeps` + +A text file containing the labels of those transitive dependencies of targets listed in +`deps` that did not contribute any object files to the static library, but do +provide at least one static, dynamic or interface library. The resulting static library +may require these libraries to be available at link time. + +##### `linkopts` + +A text file containing the user-provided `linkopts` of all transitive +dependencies of targets listed in `deps`. + +#### Duplicate symbols + +By default, the `cc_static_library` rule checks that the resulting static +library does not contain any duplicate symbols. If it does, the build fails with an error +message that lists the duplicate symbols and the object files containing them. + +This check can be disabled per target or per package by setting +`features = ["-symbol_check"]` or globally via +`--features=-symbol_check`. + +##### Toolchain support for `symbol_check` + +The auto-configured C++ toolchains shipped with Bazel support the +`symbol_check` feature on all platforms. Custom toolchains can add support for +it in one of two ways: + +* Implementing the `ACTION_NAMES.validate_static_library` action and + enabling it with the `symbol_check` feature. The tool set in the action is + invoked with two arguments, the static library to check for duplicate symbols and the + path of a file that must be created if the check passes. +* Having the `symbol_check` feature add archiver flags that cause the + action creating the static library to fail on duplicate symbols. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of targets to combine into a static library, including all their transitive dependencies. Dependencies that do not provide any object files are not included in the static library, but their labels are collected in the file provided by the `linkdeps` output group. | + +## cc_test + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_test.bzl) + +``` +cc_test(name, deps, srcs, data, additional_linker_inputs, args, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, distribs, dynamic_deps, env, env_inherit, exec_compatible_with, exec_properties, features, flaky, hdrs_check, includes, licenses, link_extra_lib, linkopts, linkshared, linkstatic, local, local_defines, malloc, module_interfaces, nocopts, reexport_deps, restricted_to, shard_count, size, stamp, tags, target_compatible_with, testonly, timeout, toolchains, visibility, win_def_file) +``` + +A `cc_test()` rule compiles a test. Here, a test +is a binary wrapper around some testing code. + +*By default, C++ tests are dynamically linked.* +To statically link a unit test, specify +[`linkstatic=True`](/reference/be/c-cpp#cc_binary.linkstatic). +It would probably be good to comment why your test needs +`linkstatic`; this is probably not obvious. + +#### Implicit output targets + +* `name.stripped` (only built if explicitly requested): A stripped + version of the binary. `strip -g` is run on the binary to remove debug + symbols. Additional strip options can be provided on the command line using + `--stripopt=-foo`. +* `name.dwp` (only built if explicitly requested): If + [Fission](https://gcc.gnu.org/wiki/DebugFission) is enabled: a debug + information package file suitable for debugging remotely deployed binaries. Else: an + empty file. + +See the [cc_binary()](/reference/be/c-cpp#cc_binary_args) arguments, except that +the `stamp` argument is set to 0 by default for tests and +that `cc_test` has extra [attributes common to all test rules (\*\_test)](/reference/be/common-definitions#common-attributes-tests). + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries to be linked in to the binary target. These can be `cc_library` or `objc_library` targets. It is also allowed to put linker scripts (.lds) into deps, and reference them in [linkopts](#cc_binary.linkopts). | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of C and C++ files that are processed to create the library target. These are C/C++ source and header files, either non-generated (normal source code) or generated. All `.cc`, `.c`, and `.cpp` files will be compiled. These might be generated files: if a named file is in the `outs` of some other rule, this `cc_library` will automatically depend on that other rule. Pure assembler files (.s, .asm) are not preprocessed and are typically built using the assembler. Preprocessed assembly files (.S) are preprocessed and are typically built using the C/C++ compiler. A `.h` file will not be compiled, but will be available for inclusion by sources in this rule. Both `.cc` and `.h` files can directly include headers listed in these `srcs` or in the `hdrs` of this rule or any rule listed in the `deps` argument. All `#include`d files must be mentioned in the `hdrs` attribute of this or referenced `cc_library` rules, or they should be listed in `srcs` if they are private to this library. See ["Header inclusion checking"](#hdrs) for a more detailed description. `.so`, `.lo`, and `.a` files are pre-compiled files. Your library might have these as `srcs` if it uses third-party code for which we don't have source code. If the `srcs` attribute includes the label of another rule, `cc_library` will use the output files of that rule as source files to compile. This is useful for one-off generation of source code (for more than occasional use, it's better to implement a Starlark rule class and use the `cc_common` API) Permitted `srcs` file types: * C and C++ source files: `.c`, `.cc`, `.cpp`, `.cxx`, `.c++`, `.C` * C and C++ header files: `.h`, `.hh`, `.hpp`, `.hxx`, `.inc`, `.inl`, `.H` * Assembler with C preprocessor: `.S` * Archive: `.a`, `.pic.a` * "Always link" library: `.lo`, `.pic.lo` * Shared library, versioned or unversioned: `.so`, `.so.version` * Object file: `.o`, `.pic.o` ... and any rules that produce those files (e.g. `cc_embed_data`). Different extensions denote different programming languages in accordance with gcc convention. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this library at runtime. See general comments about `data` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). If a `data` is the name of a generated file, then this `cc_library` rule automatically depends on the generating rule. If a `data` is a rule name, then this `cc_library` rule automatically depends on that rule, and that rule's `outs` are automatically added to this `cc_library`'s data files. Your C++ code can access these data files like so: ``` const std::string path = devtools_build::GetDataDependencyFilepath( "my/test/data/file"); ``` | +| `additional_linker_inputs` | List of [labels](/concepts/labels); default is `[]` Pass these files to the C++ linker command. For example, compiled Windows .res files can be provided here to be embedded in the binary target. | +| `conlyopts` | List of strings; default is `[]` Add these options to the C compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). | +| `copts` | List of strings; default is `[]` Add these options to the C/C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string in this attribute is added in the given order to `COPTS` before compiling the binary target. The flags take effect only for compiling this target, not its dependencies, so be careful about header files included elsewhere. All paths should be relative to the workspace, not to the current package. This attribute should not be needed outside of `third_party`. If the package declares the [feature](/reference/be/functions#package.features) `no_copts_tokenization`, Bourne shell tokenization applies only to strings that consist of a single "Make" variable. | +| `cxxopts` | List of strings; default is `[]` Add these options to the C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). | +| `defines` | List of strings; default is `[]` List of defines to add to the compile line. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line to this target, as well as to every rule that depends on it. Be very careful, since this may have far-reaching effects. When in doubt, add define values to [`local_defines`](#cc_binary.local_defines) instead. | +| `dynamic_deps` | List of [labels](/concepts/labels); default is `[]` These are other `cc_shared_library` dependencies the current target depends on. The `cc_shared_library` implementation will use the list of `dynamic_deps` (transitively, i.e. also the `dynamic_deps` of the current target's `dynamic_deps`) to decide which `cc_libraries` in the transitive `deps` should not be linked in because they are already provided by a different `cc_shared_library`. | +| `hdrs_check` | String; default is `""` Deprecated, no-op. | +| `includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-isystem path_to_package/include_entry`. This should only be used for third-party libraries that do not conform to the Google style of writing #include statements. Unlike [COPTS](#cc_binary.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When in doubt, add "-I" flags to [COPTS](#cc_binary.copts) instead. The added `include` paths will include generated files as well as files in the source tree. | +| `link_extra_lib` | [Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:link_extra_lib"` Control linking of extra libraries. By default, C++ binaries are linked against `//tools/cpp:link_extra_lib`, which by default depends on the label flag `//tools/cpp:link_extra_libs`. Without setting the flag, this library is empty by default. Setting the label flag allows linking optional dependencies, such as overrides for weak symbols, interceptors for shared library functions, or special runtime libraries (for malloc replacements, prefer `malloc` or `--custom_malloc`). Setting this attribute to `None` disables this behaviour. | +| `linkopts` | List of strings; default is `[]` Add these flags to the C++ linker command. Subject to ["Make" variable](make-variables) substitution, [Bourne shell tokenization](common-definitions#sh-tokenization) and [label expansion](common-definitions#label-expansion). Each string in this attribute is added to `LINKOPTS` before linking the binary target. Each element of this list that does not start with `$` or `-` is assumed to be the label of a target in `deps`. The list of files generated by that target is appended to the linker options. An error is reported if the label is invalid, or is not declared in `deps`. | +| `linkshared` | Boolean; default is `False` Create a shared library. To enable this attribute, include `linkshared=True` in your rule. By default this option is off. The presence of this flag means that linking occurs with the `-shared` flag to `gcc`, and the resulting shared library is suitable for loading into for example a Java program. However, for build purposes it will never be linked into the dependent binary, as it is assumed that shared libraries built with a [cc_binary](#cc_binary) rule are only loaded manually by other programs, so it should not be considered a substitute for the [cc_library](#cc_library) rule. For sake of scalability we recommend avoiding this approach altogether and simply letting `java_library` depend on `cc_library` rules instead. If you specify both `linkopts=['-static']` and `linkshared=True`, you get a single completely self-contained unit. If you specify both `linkstatic=True` and `linkshared=True`, you get a single, mostly self-contained unit. | +| `linkstatic` | Boolean; default is `False` For [`cc_binary`](/reference/be/c-cpp#cc_binary) and [`cc_test`](/reference/be/c-cpp#cc_test): link the binary in static mode. For `cc_library.link_static`: see below. By default this option is on for `cc_binary` and off for the rest. If enabled and this is a binary or test, this option tells the build tool to link in `.a`'s instead of `.so`'s for user libraries whenever possible. System libraries such as libc (but *not* the C/C++ runtime libraries, see below) are still linked dynamically, as are libraries for which there is no static library. So the resulting executable will still be dynamically linked, hence only *mostly* static. There are really three different ways to link an executable: * STATIC with fully_static_link feature, in which everything is linked statically; e.g. "`gcc -static foo.o libbar.a libbaz.a -lm`". This mode is enabled by specifying `fully_static_link` in the [`features`](/reference/be/common-definitions#features) attribute. * STATIC, in which all user libraries are linked statically (if a static version is available), but where system libraries (excluding C/C++ runtime libraries) are linked dynamically, e.g. "`gcc foo.o libfoo.a libbaz.a -lm`". This mode is enabled by specifying `linkstatic=True`. * DYNAMIC, in which all libraries are linked dynamically (if a dynamic version is available), e.g. "`gcc foo.o libfoo.so libbaz.so -lm`". This mode is enabled by specifying `linkstatic=False`. If the `linkstatic` attribute or `fully_static_link` in `features` is used outside of `//third_party` please include a comment near the rule to explain why. The `linkstatic` attribute has a different meaning if used on a [`cc_library()`](/reference/be/c-cpp#cc_library) rule. For a C++ library, `linkstatic=True` indicates that only static linking is allowed, so no `.so` will be produced. linkstatic=False does not prevent static libraries from being created. The attribute is meant to control the creation of dynamic libraries. There should be very little code built with `linkstatic=False` in production. If `linkstatic=False`, then the build tool will create symlinks to depended-upon shared libraries in the `*.runfiles` area. | +| `local_defines` | List of strings; default is `[]` List of defines to add to the compile line. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line for this target, but not to its dependents. | +| `malloc` | [Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:malloc"` Override the default dependency on malloc. By default, C++ binaries are linked against `//tools/cpp:malloc`, which is an empty library so the binary ends up using libc malloc. This label must refer to a `cc_library`. If compilation is for a non-C++ rule, this option has no effect. The value of this attribute is ignored if `linkshared=True` is specified. | +| `module_interfaces` | List of [labels](/concepts/labels); default is `[]` The list of files are regarded as C++20 Modules Interface. C++ Standard has no restriction about module interface file extension * Clang use cppm * GCC can use any source file extension * MSVC use ixx The use is guarded by the flag `--experimental_cpp_modules`. | +| `nocopts` | String; default is `""` Remove matching options from the C++ compilation command. Subject to ["Make" variable](/reference/be/make-variables) substitution. The value of this attribute is interpreted as a regular expression. Any preexisting `COPTS` that match this regular expression (including values explicitly specified in the rule's [copts](#cc_binary.copts) attribute) will be removed from `COPTS` for purposes of compiling this rule. This attribute should not be needed or used outside of `third_party`. The values are not preprocessed in any way other than the "Make" variable substitution. | +| `reexport_deps` | List of [labels](/concepts/labels); default is `[]` | +| `stamp` | Integer; default is `0` Whether to encode build information into the binary. Possible values: * `stamp = 1`: Always stamp the build information into the binary, even in [`--nostamp`](/docs/user-manual#flag--stamp) builds. **This setting should be avoided**, since it potentially kills remote caching for the binary and any downstream actions that depend on it. * `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`](/docs/user-manual#flag--stamp) flag. Stamped binaries are *not* rebuilt unless their dependencies change. | +| `win_def_file` | [Label](/concepts/labels); default is `None` The Windows DEF file to be passed to linker. This attribute should only be used when Windows is the target platform. It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. | + +## cc_toolchain + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_toolchain.bzl) + +``` +cc_toolchain(name, all_files, ar_files, as_files, compatible_with, compiler_files, compiler_files_without_includes, coverage_files, deprecation, distribs, dwp_files, dynamic_runtime_lib, exec_compatible_with, exec_properties, exec_transition_for_inputs, features, libc_top, licenses, linker_files, module_map, objcopy_files, output_licenses, restricted_to, static_runtime_lib, strip_files, supports_header_parsing, supports_param_files, tags, target_compatible_with, testonly, toolchain_config, toolchain_identifier, toolchains, visibility) +``` + +Represents a C++ toolchain. + +This rule is responsible for: + +* Collecting all artifacts needed for C++ actions to run. This is done by + attributes such as `all_files`, `compiler_files`, + `linker_files`, or other attributes ending with `_files`). These are + most commonly filegroups globbing all required files. +* Generating correct command lines for C++ actions. This is done using + `CcToolchainConfigInfo` provider (details below). + +Use `toolchain_config` attribute to configure the C++ toolchain. +See also this +[page](https://bazel.build/docs/cc-toolchain-config-reference) for elaborate C++ toolchain configuration and toolchain selection documentation. + +Use `tags = ["manual"]` in order to prevent toolchains from being built and configured +unnecessarily when invoking `bazel build //...` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `all_files` | [Label](/concepts/labels); required Collection of all cc_toolchain artifacts. These artifacts will be added as inputs to all rules_cc related actions (with the exception of actions that are using more precise sets of artifacts from attributes below). Bazel assumes that `all_files` is a superset of all other artifact-providing attributes (e.g. linkstamp compilation needs both compile and link files, so it takes `all_files`). This is what `cc_toolchain.files` contains, and this is used by all Starlark rules using C++ toolchain. | +| `ar_files` | [Label](/concepts/labels); default is `None` Collection of all cc_toolchain artifacts required for archiving actions. | +| `as_files` | [Label](/concepts/labels); default is `None` Collection of all cc_toolchain artifacts required for assembly actions. | +| `compiler_files` | [Label](/concepts/labels); required Collection of all cc_toolchain artifacts required for compile actions. | +| `compiler_files_without_includes` | [Label](/concepts/labels); default is `None` Collection of all cc_toolchain artifacts required for compile actions in case when input discovery is supported (currently Google-only). | +| `coverage_files` | [Label](/concepts/labels); default is `None` Collection of all cc_toolchain artifacts required for coverage actions. If not specified, all_files are used. | +| `dwp_files` | [Label](/concepts/labels); required Collection of all cc_toolchain artifacts required for dwp actions. | +| `dynamic_runtime_lib` | [Label](/concepts/labels); default is `None` Dynamic library artifact for the C++ runtime library (e.g. libstdc++.so). This will be used when 'static_link_cpp_runtimes' feature is enabled, and we're linking dependencies dynamically. | +| `exec_transition_for_inputs` | Boolean; default is `False` Deprecated. No-op. | +| `libc_top` | [Label](/concepts/labels); default is `None` A collection of artifacts for libc passed as inputs to compile/linking actions. | +| `linker_files` | [Label](/concepts/labels); required Collection of all cc_toolchain artifacts required for linking actions. | +| `module_map` | [Label](/concepts/labels); default is `None` Module map artifact to be used for modular builds. | +| `objcopy_files` | [Label](/concepts/labels); required Collection of all cc_toolchain artifacts required for objcopy actions. | +| `output_licenses` | List of strings; default is `[]` | +| `static_runtime_lib` | [Label](/concepts/labels); default is `None` Static library artifact for the C++ runtime library (e.g. libstdc++.a). This will be used when 'static_link_cpp_runtimes' feature is enabled, and we're linking dependencies statically. | +| `strip_files` | [Label](/concepts/labels); required Collection of all cc_toolchain artifacts required for strip actions. | +| `supports_header_parsing` | Boolean; default is `False` Set to True when cc_toolchain supports header parsing actions. | +| `supports_param_files` | Boolean; default is `True` Set to True when cc_toolchain supports using param files for linking actions. | +| `toolchain_config` | [Label](/concepts/labels); required The label of the rule providing `cc_toolchain_config_info`. | +| `toolchain_identifier` | String; default is `""` The identifier used to match this cc_toolchain with the corresponding crosstool_config.toolchain. Until issue [#5380](https://github.com/bazelbuild/bazel/issues/5380) is fixed this is the recommended way of associating `cc_toolchain` with `CROSSTOOL.toolchain`. It will be replaced by the `toolchain_config` attribute ([#5380](https://github.com/bazelbuild/bazel/issues/5380)). | + +## cc_toolchain_suite + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/cpp/CcToolchainSuiteRule.java) + +``` +cc_toolchain_suite(name, compatible_with, deprecation, distribs, features, licenses, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Deprecated: the rule is a no-op and will be removed. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | + +## fdo_prefetch_hints + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/fdo/fdo_prefetch_hints.bzl) + +``` +fdo_prefetch_hints(name, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Represents an FDO prefetch hints profile that is either in the workspace. +Examples: + +``` +fdo_prefetch_hints( + name = "hints", + profile = "//path/to/hints:profile.afdo", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `profile` | [Label](/concepts/labels); required Label of the hints profile. The hints file has the .afdo extension The label can also point to an fdo_absolute_path_profile rule. | + +## fdo_profile + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/fdo/fdo_profile.bzl) + +``` +fdo_profile(name, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, memprof_profile, profile, proto_profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Represents an FDO profile that is in the workspace. +Example: + +``` +fdo_profile( + name = "fdo", + profile = "//path/to/fdo:profile.zip", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `memprof_profile` | [Label](/concepts/labels); default is `None` Label of the MemProf profile. The profile is expected to have either a .profdata extension (for an indexed/symbolized memprof profile), or a .zip extension for a zipfile containing a memprof.profdata file. | +| `profile` | [Label](/concepts/labels); required Label of the FDO profile or a rule which generates it. The FDO file can have one of the following extensions: .profraw for unindexed LLVM profile, .profdata for indexed LLVM profile, .zip that holds an LLVM profraw profile, .afdo for AutoFDO profile, .xfdo for XBinary profile. The label can also point to an fdo_absolute_path_profile rule. | +| `proto_profile` | [Label](/concepts/labels); default is `None` Label of the protobuf profile. | + +## memprof_profile + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/fdo/memprof_profile.bzl) + +``` +memprof_profile(name, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Represents a MEMPROF profile that is in the workspace. +Example: + +``` +memprof_profile( + name = "memprof", + profile = "//path/to/memprof:profile.afdo", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `profile` | [Label](/concepts/labels); required Label of the MEMPROF profile. The profile is expected to have either a .profdata extension (for an indexed/symbolized memprof profile), or a .zip extension for a zipfile containing a memprof.profdata file. The label can also point to an fdo_absolute_path_profile rule. | + +## propeller_optimize + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/fdo/propeller_optimize.bzl) + +``` +propeller_optimize(name, cc_profile, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, ld_profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Represents a Propeller optimization profile in the workspace. +Example: + +``` +propeller_optimize( + name = "layout", + cc_profile = "//path:cc_profile.txt", + ld_profile = "//path:ld_profile.txt" +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `cc_profile` | [Label](/concepts/labels); required Label of the profile passed to the various compile actions. This file has the .txt extension. | +| `ld_profile` | [Label](/concepts/labels); required Label of the profile passed to the link action. This file has the .txt extension. | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/common-definitions.mdx b/versions/8.6.0/reference/be/common-definitions.mdx new file mode 100644 index 00000000..477750fb --- /dev/null +++ b/versions/8.6.0/reference/be/common-definitions.mdx @@ -0,0 +1,209 @@ +--- +title: 'Common definitions' +--- + +This section defines various terms and concepts that are common to +many functions or build rules. + +## Contents + +* [Bourne shell tokenization](#sh-tokenization) +* [Label Expansion](#label-expansion) +* [Typical attributes defined by most build rules](#typical-attributes) +* [Attributes common to all build rules](#common-attributes) +* [Attributes common to all test rules (\*\_test)](#common-attributes-tests) +* [Attributes common to all binary rules (\*\_binary)](#common-attributes-binaries) +* [Configurable attributes](#configurable-attributes) +* [Implicit output targets](#implicit-outputs) + +## Bourne shell tokenization + +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. Examples of such attributes are +`cc_library.copts` and `java_library.javacopts`. +Together these substitutions allow a +single string variable to expand into a configuration-specific list +of option words. + +## Label expansion + +Some string attributes of a very few rules are subject to label +expansion: if those strings contain a valid 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](https://bazel.build/reference/glossary#target) +`//mypkg:target`. + +Example attributes include `genrule.cmd` and +`cc_binary.linkopts`. 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. + +## Typical attributes defined by most build rules + +This section describes attributes that are defined by many build rules, +but not all. + +| Attribute | Description | +| --- | --- | +| `data` | List of [labels](/concepts/labels); default is `[]` Files needed by this rule at runtime. May list file or rule targets. Generally allows any target. The default outputs and runfiles of targets in the `data` attribute should appear in the `*.runfiles` area of any executable which is output by or has a runtime dependency on this target. This may include data files or binaries used when this target's [`srcs`](#typical.srcs) are executed. See the [data dependencies](/concepts/dependencies#data-dependencies) section for more information about how to depend on and use data files. New rules should define a `data` attribute if they process inputs which might use other inputs at runtime. Rules' implementation functions must also [populate the target's runfiles](https://bazel.build/rules/rules#runfiles) from the outputs and runfiles of any `data` attribute, as well as runfiles from any dependency attribute which provides either source code or runtime dependencies. | +| `deps` | List of [labels](/concepts/labels); default is `[]` Dependencies for this target. Generally should only list rule targets. (Though some rules permit files to be listed directly in `deps`, this should be avoided when possible.) Language-specific rules generally limit the listed targets to those with specific [providers](https://bazel.build/extending/rules#providers). The precise semantics of what it means for a target to depend on another using `deps` are specific to the kind of rule, and the rule-specific documentation goes into more detail. For rules which process source code, `deps` generally specifies code dependencies used by the code in [`srcs`](#typical.srcs). 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` target may depend on C++ code in a `cc_library` target, by listing the latter in the `deps` attribute. See the definition of [dependencies](/concepts/build-ref#deps) for more information. | +| `licenses` | List of strings; [nonconfigurable](#configurable-attributes); default is `["none"]` A list of license-type strings to be used for this particular target. This is part of a deprecated licensing API that Bazel no longer uses. Don't use this. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` Files processed or included by this rule. Generally lists files directly, but may list rule targets (like `filegroup` or `genrule`) to include their default outputs. Language-specific rules often require that the listed files have particular file extensions. | + +## Attributes common to all build rules + +This section describes attributes that are implicitly added to all build +rules. + +| Attribute | Description | +| --- | --- | +| `compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` The list of environments this target can be built for, in addition to default-supported environments. This is part of Bazel's constraint system, which lets users declare which targets can and cannot depend on each other. For example, externally deployable binaries shouldn't depend on libraries with company-secret code. See [ConstraintSemantics](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/analysis/constraints/ConstraintSemantics.java#L46) for details. | +| `deprecation` | String; [nonconfigurable](#configurable-attributes); default is `None` An explanatory warning message associated with this target. Typically this is used to notify users that a target has become obsolete, or has become superseded by another rule, is private to a package, or is perhaps considered harmful for some reason. It is a good idea to include some reference (like a webpage, a bug number or example migration CLs) so that one can easily find out what changes are required to avoid the message. If there is a new target that can be used as a drop in replacement, it is a good idea to just migrate all users of the old target. 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 a target in another package. 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 target depends on another deprecated target, no warning message is issued. Once people have stopped using it, the target can be removed. | +| `distribs` | List of strings; [nonconfigurable](#configurable-attributes); default is `[]` A list of distribution-method strings to be used for this particular target. This is part of a deprecated licensing API that Bazel no longer uses. Don't use this. | +| `exec_compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` A list of `constraint_values` that must be present in the execution platform for this target. This is in addition to any constraints already set by the rule type. Constraints are used to restrict the list of available execution platforms. For more details, see the description of [toolchain resolution](/docs/toolchains#toolchain-resolution). | +| `exec_properties` | Dictionary of strings; default is `{}` A dictionary of strings that will be added to the `exec_properties` of a platform selected for this target. See `exec_properties` of the [platform](platforms-and-toolchains#platform) rule. If a key is present in both the platform and target-level properties, the value will be taken from the target. | +| `features` | List of *feature* strings; default is `[]` A feature is string tag that can be enabled or disabled on a target. The meaning of a feature depends on the rule itself. This `features` attribute is combined with the [package](/reference/be/functions#package) level `features` attribute. For example, if the features ["a", "b"] are enabled on the package level, and a target's `features` attribute contains ["-a", "c"], the features enabled for the rule will be "b" and "c". [See example](https://github.com/bazelbuild/examples/blob/main/rules/features/BUILD). | +| `restricted_to` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` The list of environments this target can be built for, *instead* of default-supported environments. This is part of Bazel's constraint system. See `compatible_with` for details. | +| `tags` | List of strings; [nonconfigurable](#configurable-attributes); default is `[]` *Tags* can be used on any rule. *Tags* on test and `test_suite` rules are useful for categorizing the tests. *Tags* on non-test targets are used to control sandboxed execution of `genrule`s and [Starlark](/rules/concepts) actions, and for parsing by humans and/or external tools. Bazel modifies the behavior of its sandboxing code if it finds the following keywords in the `tags` attribute of any test or `genrule` target, or the keys of `execution_requirements` for any Starlark action. * `no-sandbox` keyword results in the action or test never being sandboxed; it can still be cached or run remotely - use `no-cache` or `no-remote` to prevent either or both of those. * `no-cache` keyword results in the action or test never being cached (locally or remotely). Note: for the purposes of this tag, the disk cache is considered a local cache, whereas the HTTP and gRPC caches are considered remote. Other caches, such as Skyframe or the persistent action cache, are not affected. * `no-remote-cache` keyword results in the action or test never being cached remotely (but it may be cached locally; it may also be executed remotely). Note: for the purposes of this tag, the disk cache is considered a local cache, whereas the HTTP and gRPC caches are considered remote. Other caches, such as Skyframe or the persistent action cache, are not affected. If a combination of local disk cache and remote cache are used (combined cache), it's treated as a remote cache and disabled entirely unless `--incompatible_remote_results_ignore_disk` is set in which case the local components will be used. * `no-remote-exec` keyword results in the action or test never being executed remotely (but it may be cached remotely). * `no-remote` keyword prevents the action or test from being executed remotely or cached remotely. This is equivalent to using both `no-remote-cache` and `no-remote-exec`. * `no-remote-cache-upload` keyword disables upload part of remote caching of a spawn. it does not disable remote execution. * `local` keyword precludes the action or test from being remotely cached, remotely executed, or run inside the sandbox. For genrules and tests, marking the rule with the `local = True` attribute has the same effect. * `requires-network` keyword allows access to the external network from inside the sandbox. This tag only has an effect if sandboxing is enabled. * `block-network` keyword blocks access to the external network from inside the sandbox. In this case, only communication with localhost is allowed. This tag only has an effect if sandboxing is enabled. * `requires-fakeroot` runs the test or action as uid and gid 0 (i.e., the root user). This is only supported on Linux. This tag takes precedence over the `--sandbox_fake_username` command-line option. *Tags* on tests are generally used to annotate a test's role in your debug and release process. Typically, tags are most useful for C++ and Python tests, which lack any runtime annotation ability. The use of tags and size elements gives flexibility in assembling suites of tests based around codebase check-in policy. Bazel modifies test running behavior if it finds the following keywords in the `tags` attribute of the test rule: * `exclusive` will force the test to be run in the "exclusive" mode, ensuring that no other tests are running at the same time. Such tests will be executed in serial fashion after all build activity and non-exclusive tests have been completed. Remote execution is disabled for such tests because Bazel doesn't have control over what's running on a remote machine. * `exclusive-if-local` will force the test to be run in the "exclusive" mode if it is executed locally, but will run the test in parallel if it's executed remotely. * `manual` keyword will exclude the target from expansion of target pattern wildcards (`...`, `:*`, `:all`, etc.) and `test_suite` rules which do not list the test explicitly when computing the set of top-level targets to build/run for the `build`, `test`, and `coverage` commands. It does not affect target wildcard or test suite expansion in other contexts, including the `query` command. Note that `manual` does not imply that a target should not be built/run automatically by continuous build/test systems. For example, it may be desirable to exclude a target from `bazel test ...` because it requires specific Bazel flags, but still have it included in properly-configured presubmit or continuous test runs. * `external` keyword will force test to be unconditionally executed (regardless of `--cache_test_results` value). See [Tag Conventions](/reference/test-encyclopedia#tag-conventions) in the Test Encyclopedia for more conventions on tags attached to test targets. | +| `target_compatible_with` | List of [labels](/concepts/labels); default is `[]` A list of `constraint_value`s that must be present in the target platform for this target to be considered *compatible*. This is in addition to any constraints already set by the rule type. If the target platform does not satisfy all listed constraints then the target is considered *incompatible*. Incompatible targets are skipped for building and testing when the target pattern is expanded (e.g. `//...`, `:all`). When explicitly specified on the command line, incompatible targets cause Bazel to print an error and cause a build or test failure. Targets that transitively depend on incompatible targets are themselves considered incompatible. They are also skipped for building and testing. An empty list (which is the default) signifies that the target is compatible with all platforms. All rules other than [Workspace Rules](workspace) support this attribute. For some rules this attribute has no effect. For example, specifying `target_compatible_with` for a `cc_toolchain` is not useful. See the [Platforms](/docs/platforms#skipping-incompatible-targets) page for more information about incompatible target skipping. | +| `testonly` | Boolean; [nonconfigurable](#configurable-attributes); default is `False` except for test and test suite targets If `True`, only testonly targets (such as tests) can depend on this target. 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](/reference/be/general#test_suite) rules) 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. | +| `toolchains` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` The set of targets whose [Make variables](/reference/be/make-variables) this target is allowed to access. These targets are either instances of rules that provide `TemplateVariableInfo` or special targets for toolchain types built into Bazel. These include: * `@bazel_tools//tools/cpp:current_cc_toolchain`* `@rules_java//toolchains:current_java_runtime` Note that this is distinct from the concept of [toolchain resolution](/docs/toolchains#toolchain-resolution) that is used by rule implementations for platform-dependent configuration. You cannot use this attribute to determine which specific `cc_toolchain` or `java_toolchain` a target will use. | +| `visibility` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default varies The `visibility` attribute controls whether the target can be depended on by targets in other locations. See the documentation for [visibility](/concepts/visibility). For targets declared directly in a BUILD file or in legacy macros called from a BUILD file, the default value is the package's `default_visibility` if specified, or else `["//visibility:private"]`. For targets declared in one or more symbolic macros, the default value is always just `["//visibility:private"]` (which makes it useable only within the package containing the macro's code). | + +## Attributes common to all test rules (\*\_test) + +This section describes attributes that are common to all test rules. + +| Attribute | Description | +| --- | --- | +| `args` | List of strings; subject to [$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution, and [Bourne shell tokenization](#sh-tokenization); default is `[]` Command line arguments that Bazel passes to the target when it is executed with `bazel test`. These arguments are passed before any `--test_arg` values specified on the `bazel test` command line. | +| `env` | Dictionary of strings; values are subject to [$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution; default is `{}` Specifies additional environment variables to set when the test is executed by `bazel test`. This attribute only applies to native rules, like `cc_test`, `py_test`, and `sh_test`. It does not apply to Starlark-defined test rules. For your own Starlark rules, you can add an "env" attribute and use it to populate a [TestEnvironment](/rules/lib/toplevel/testing#TestEnvironment) Provider. | +| `env_inherit` | List of strings; default is `[]` Specifies additional environment variables to inherit from the external environment when the test is executed by `bazel test`. This attribute only applies to native rules, like `cc_test`, `py_test`, and `sh_test`. It does not apply to Starlark-defined test rules. | +| `size` | String `"enormous"`, `"large"`, `"medium"`, or `"small"`; [nonconfigurable](#configurable-attributes); default is `"medium"` Specifies a test target's "heaviness": how much time/resources it needs to run. Unit tests are considered "small", integration tests "medium", and end-to-end tests "large" or "enormous". Bazel uses the size to determine a default timeout, which can be overridden using the `timeout` attribute. The timeout is for all tests in the BUILD target, not for each individual test. When the test is run locally, the `size` is additionally used for scheduling purposes: Bazel tries to respect `--local_{ram,cpu}_resources` and not overwhelm the local machine by running lots of heavy tests at the same time. Test sizes correspond to the following default timeouts and assumed peak local resource usages: | Size | RAM (in MB) | CPU (in CPU cores) | Default timeout | | --- | --- | --- | --- | | small | 20 | 1 | short (1 minute) | | medium | 100 | 1 | moderate (5 minutes) | | large | 300 | 1 | long (15 minutes) | | enormous | 800 | 1 | eternal (60 minutes) | The environment variable `TEST_SIZE` will be set to the value of this attribute when spawning the test. | +| `timeout` | String `"short"`, `"moderate"`, `"long"`, or `"eternal"`; [nonconfigurable](#configurable-attributes); default is derived from the test's `size` attribute How long the test is expected to run before returning. While a test's size attribute controls resource estimation, a test's timeout may be set independently. If not explicitly specified, the timeout is based on the [test's size](#test.size). The test timeout can be overridden with the `--test_timeout` flag, e.g. for running under certain conditions which are known to be slow. Test timeout values correspond to the following time periods: | Timeout Value | Time Period | | --- | --- | | short | 1 minute | | moderate | 5 minutes | | long | 15 minutes | | eternal | 60 minutes | For times other than the above, the test timeout can be overridden with the `--test_timeout` bazel flag, e.g. for manually running under conditions which are known to be slow. The `--test_timeout` values are in seconds. For example `--test_timeout=120` will set the test timeout to two minutes. The environment variable `TEST_TIMEOUT` will be set to the test timeout (in seconds) when spawning the test. | +| `flaky` | Boolean; [nonconfigurable](#configurable-attributes); default is `False` Marks test as flaky. If set, executes the test up to three times, marking it as failed only if it fails each time. By default, this attribute is set to False and the test is executed only once. Note, that use of this attribute is generally discouraged - tests should pass reliably when their assertions are upheld. | +| `shard_count` | Non-negative integer less than or equal to 50; default is `-1` Specifies the number of parallel shards to use to run the test. If set, this value will override any heuristics used to determine the number of parallel shards with which to run the test. Note that for some test rules, this parameter may be required to enable sharding in the first place. Also see `--test_sharding_strategy`. If test sharding is enabled, the environment variable `TEST_TOTAL_SHARDS` will be set to this value when spawning the test. Sharding requires the test runner to support the test sharding protocol. If it does not, then it will most likely run every test in every shard, which is not what you want. See [Test Sharding](/reference/test-encyclopedia#test-sharding) in the Test Encyclopedia for details on sharding. | +| `local` | Boolean; [nonconfigurable](#configurable-attributes); default is `False` Forces the test to be run locally, without sandboxing. Setting this to True is equivalent to providing "local" as a tag (`tags=["local"]`). | + +## Attributes common to all binary rules (\*\_binary) + +This section describes attributes that are common to all binary rules. + +| Attribute | Description | +| --- | --- | +| `args` | List of strings; subject to [$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution, and [Bourne shell tokenization](#sh-tokenization); [nonconfigurable](#configurable-attributes); default is `[]` Command line arguments that Bazel will pass to the target when it is executed either by the `run` command or as a test. These arguments are passed before the ones that are specified on the `bazel run` or `bazel test` command line. *NOTE: The arguments are not passed when you run the target outside of Bazel (for example, by manually executing the binary in `bazel-bin/`).* | +| `env` | Dictionary of strings; values are subject to [$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution; default is `{}` Specifies additional environment variables to set when the target is executed by `bazel run`. This attribute only applies to native rules, like `cc_binary`, `py_binary`, and `sh_binary`. It does not apply to Starlark-defined executable rules. *NOTE: The environment variables are not set when you run the target outside of Bazel (for example, by manually executing the binary in `bazel-bin/`).* | +| `output_licenses` | List of strings; default is `[]` The licenses of the output files that this binary generates. This is part of a deprecated licensing API that Bazel no longer uses. Don't use this. | + +## Configurable attributes + +Most attributes are "configurable", meaning that their values may change when +the target is built in different ways. Specifically, configurable attributes +may vary based on the flags passed to the Bazel command line, or what +downstream dependency is requesting the target. This can be used, for +instance, to customize the target for multiple platforms or compilation modes. + +The following example declares different sources for different target +architectures. Running `bazel build :multiplatform_lib --cpu x86` +will build the target using `x86_impl.cc`, while substituting +`--cpu arm` will instead cause it to use `arm_impl.cc`. + +``` +cc_library( + name = "multiplatform_lib", + srcs = select({ + ":x86_mode": ["x86_impl.cc"], + ":arm_mode": ["arm_impl.cc"] + }) +) +config_setting( + name = "x86_mode", + values = { "cpu": "x86" } +) +config_setting( + name = "arm_mode", + values = { "cpu": "arm" } +) +``` + +The [`select()`](/reference/be/functions#select) function +chooses among different alternative values for a configurable attribute based +on which [`config_setting`](/reference/be/general#config_setting) +or [`constraint_value`](/reference/be/platforms-and-toolchains#constraint_value) +criteria the target's configuration satisfies. + +Bazel evaluates configurable attributes after processing macros and before +processing rules (technically, between the +[loading and analysis phases](https://bazel.build/rules/concepts#evaluation-model)). +Any processing before `select()` evaluation doesn't know which +branch the `select()` chooses. Macros, for example, can't change +their behavior based on the chosen branch, and `bazel query` can +only make conservative guesses about a target's configurable dependencies. See +[this FAQ](https://bazel.build/docs/configurable-attributes#faq) +for more on using `select()` with rules and macros. + +Attributes marked `nonconfigurable` in their documentation cannot +use this feature. Usually an attribute is nonconfigurable because Bazel +internally needs to know its value before it can determine how to resolve a +`select()`. + +See [Configurable Build Attributes](https://bazel.build/docs/configurable-attributes) for a detailed overview. + +## Implicit output targets + +*Implicit outputs in C++ are deprecated. Please refrain from using it +in other languages where possible. We don't have a deprecation path yet +but they will eventually be deprecated too.* + +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 global +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. + +An important but somewhat subtle distinction between the +two namespaces used by the build system: +[labels](/concepts/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](/concepts/build-ref). \ No newline at end of file diff --git a/versions/8.6.0/reference/be/extra-actions.mdx b/versions/8.6.0/reference/be/extra-actions.mdx new file mode 100644 index 00000000..8a293581 --- /dev/null +++ b/versions/8.6.0/reference/be/extra-actions.mdx @@ -0,0 +1,106 @@ +--- +title: 'Extra Actions Rules' +--- + +## Rules + +* [action_listener](#action_listener) +* [extra_action](#extra_action) + +## action_listener + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/extra/ActionListenerRule.java) + +``` +action_listener(name, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, extra_actions, features, licenses, mnemonics, restricted_to, tags, target_compatible_with, testonly, visibility) +``` + +**WARNING:** Extra actions are deprecated. Use +[aspects](https://bazel.build/rules/aspects) +instead. + +An `action_listener` rule doesn't produce any output itself. +Instead, it allows tool developers to insert +[`extra_action`](/reference/be/extra-actions#extra_action)s into the build system, +by providing a mapping from action to [`extra_action`](/reference/be/extra-actions#extra_action). + +This rule's arguments map action mnemonics to +[`extra_action`](/reference/be/extra-actions#extra_action) rules. + +By specifying the option [`--experimental_action_listener=<label>`](/docs/user-manual#flag--experimental_action_listener), +the build will use the specified `action_listener` to insert +[`extra_action`](/reference/be/extra-actions#extra_action)s into the build graph. + +#### Example + +``` +action_listener( + name = "index_all_languages", + mnemonics = [ + "Javac", + "CppCompile", + "Python", + ], + extra_actions = [":indexer"], +) + +action_listener( + name = "index_java", + mnemonics = ["Javac"], + extra_actions = [":indexer"], +) + +extra_action( + name = "indexer", + tools = ["//my/tools:indexer"], + cmd = "$(location //my/tools:indexer)" + + "--extra_action_file=$(EXTRA_ACTION_FILE)", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `extra_actions` | List of [labels](/concepts/labels); required A list of `extra_action` targets this `action_listener` should add to the build graph. E.g. `[ "//my/tools:analyzer" ]`. | +| `mnemonics` | List of strings; required A list of action mnemonics this `action_listener` should listen for, e.g. `[ "Javac" ]`. Mnemonics are not a public interface. There's no guarantee that the mnemonics and their actions don't change. | + +## extra_action + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/extra/ExtraActionRule.java) + +``` +extra_action(name, data, cmd, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, licenses, out_templates, requires_action_output, restricted_to, tags, target_compatible_with, testonly, toolchains, tools, visibility) +``` + +**WARNING:** Extra actions are deprecated. Use +[aspects](https://bazel.build/rules/aspects) +instead. + +An `extra_action` rule doesn't produce any meaningful output +when specified as a regular build target. Instead, it allows tool developers +to insert additional actions into the build graph that shadow existing actions. + +See [`action_listener`](/reference/be/extra-actions#action_listener) for details +on how to enable `extra_action`s. + +The `extra_action`s run as a command-line. The command-line tool gets +access to a file containing a protocol buffer as $(EXTRA_ACTION_FILE) +with detailed information on the original action it is shadowing. +It also has access to all the input files the original action has access to. +See extra_actions_base.proto +for details on the data stored inside the protocol buffer. Each proto file +contains an ExtraActionInfo message. + +Just like all other actions, extra actions are sandboxed, and should be designed to handle that. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. You may refer to this rule by `label` in the `extra_actions` argument of [`action_listener`](/reference/be/extra-actions#action_listener) rules. | +| `cmd` | String; required The command to run. Like [genrule cmd attribute](/reference/be/general#genrule.cmd) with the following differences: 1. No heuristic label expansion. Only labels using $(location ...) are expanded. 2. An additional pass is applied to the string to replace all occurrences of the outputs created from the `out_templates` attribute. All occurrences of `$(output out_template)` are replaced with the path to the file denoted by `label`. E.g. out_template `$(ACTION_ID).analysis` can be matched with `$(output $(ACTION_ID).analysis)`. In effect, this is the same substitution as `$(location)` but with a different scope. | +| `out_templates` | List of strings; default is `[]` A list of templates for files generated by the `extra_action` command. The template can use the following variables: * $(ACTION_ID), an id uniquely identifying this `extra_action`. Used to generate a unique output file. | +| `requires_action_output` | Boolean; default is `False` Indicates this `extra_action` requires the output of the original action to be present as input to this `extra_action`. When true (default false), the extra_action can assume that the original action outputs are available as part of its inputs. | +| `tools` | List of [labels](/concepts/labels); default is `[]` A list of `tool` dependencies for this rule. See the definition of [dependencies](/concepts/build-ref#deps) for more information. The build system ensures these prerequisites are built before running the `extra_action` command; they are built using the [`exec`configuration](/docs/user-manual#configurations), since they must run as a tool during the build itself. The path of an individual `tools` target `//x:y` can be obtained using `$(location //x:y)`. All tools and their data dependencies are consolidated into a single tree within which the command can use relative paths. The working directory will be the root of that unified tree. | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/functions.mdx b/versions/8.6.0/reference/be/functions.mdx new file mode 100644 index 00000000..e7c75155 --- /dev/null +++ b/versions/8.6.0/reference/be/functions.mdx @@ -0,0 +1,532 @@ +--- +title: 'Functions' +--- + +## Contents + +* [package](#package) +* [package_group](#package_group) +* [exports_files](#exports_files) +* [glob](#glob) +* [select](#select) +* [subpackages](#subpackages) + +## package + +``` +package(default_deprecation, default_package_metadata, default_testonly, default_visibility, features) +``` + +This function declares metadata that applies to every rule in the +package. It is used at most once within a package (BUILD file). + +For the counterpart that declares metadata applying to every rule in the whole +*repository*, use the `repo()` function in the +[`REPO.bazel` file](/external/overview#repo.bazel) at the root of your repo. +The `repo()` function takes exactly the same arguments as `package()`. + +The package() function should be called right after all the load() statements at the top of the +file, before any rule. + +### Arguments + +| Attribute | Description | +| --- | --- | +| `default_applicable_licenses` | Alias for [`default_package_metadata`](#package.default_package_metadata). | +| `default_visibility` | List of [labels](/concepts/labels); default is `[]` The default visibility of the top-level rule targets and symbolic macros in this package — that is, the targets and symbolic macros that are not themselves declared inside a symbolic macro. This attribute is ignored if the target or macro specifies a `visibility` value. For detailed information about the syntax of this attribute, see the documentation of [visibility](/concepts/visibility). The package default visibility does not apply to [exports_files](#exports_files), which is public by default. | +| `default_deprecation` | String; default is `""` Sets the default [`deprecation`](common-definitions#common.deprecation) message for all rules in this package. | +| `default_package_metadata` | List of [labels](/concepts/labels); default is `[]` Sets a default list of metadata targets which apply to all other targets in the package. These are typically targets related to OSS package and license declarations. See [rules_license](https://github.com/bazelbuild/rules_license) for examples. | +| `default_testonly` | Boolean; default is `False` except as noted Sets the default [`testonly`](common-definitions#common.testonly) property for all rules in this package. In packages under `javatests` the default value is `True`. | +| `features` | List strings; default is `[]` Sets various flags that affect the semantics of this BUILD file. This feature is mainly used by the people working on the build system to tag packages that need some kind of special handling. Do not use this unless explicitly requested by someone working on the build system. | + +### Examples + +The declaration below declares that the rules in this package are +visible only to members of package +group `//foo:target`. Individual visibility declarations +on a rule, if present, override this specification. + +``` +package(default_visibility = ["//foo:target"]) +``` + +## package_group + +``` +package_group(name, packages, includes) +``` + +This function defines a set of [packages](/concepts/build-ref#packages) +and associates a label with the set. The label can be referenced in +`visibility` attributes. + +Package groups are primarily used for visibility control. A publicly visible +target can be referenced from every package in the source tree. A privately +visible target can only be referenced within its own package (not subpackages). +In between these extremes, a target may allow access to its own package plus any +of the packages described by one or more package groups. For a more detailed +explanation of the visibility system, see the +[visibility](common-definitions#common.visibility) +attribute. + +A given package is considered to be in the group if it either matches the +`packages` attribute, or is already contained in one of the other +package groups mentioned in the `includes` attribute. + +Package groups are technically targets, but are not created by rules, and do +not themselves have any visibility protection. + +### Arguments + +| Attribute | Description | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `packages` | List of strings; default is `[]` A list of zero or more package specifications. Each package specification string can have one of the following forms: 1. The full name of a package, without its repository, starting with a double slash. For example, `//foo/bar` specifies the package having that name and which lives in the same repository as the package group.- As above, but with a trailing `/...`. For example, `//foo/...` specifies the set of `//foo` and all its subpackages. `//...` specifies all packages in the current repository.- The strings `public` or `private`, which respectively specify every package or no package. (This form requires the flag `--incompatible_package_group_has_public_syntax` to be set.) In addition, the first two kinds of package specifications may also be prefixed with `-` to indicate that they are negated. The package group contains any package that matches at least one of its positive specifications and none of its negative specifications For instance, the value `[//foo/..., -//foo/tests/...]` includes all subpackages of `//foo` that are not also subpackages of `//foo/tests`. (`//foo` itself is included while //foo/tests itself is not.) Aside from public visibility, there is no way to directly specify packages outside the current repository. If this attribute is missing, it is the same as setting it to an empty list, which is also the same as setting it to a list containing only `private`. *Note:* Prior to Bazel 6.0, the specification `//...` had a legacy behavior of being the same as `public`. This behavior is fixed when `--incompatible_fix_package_group_reporoot_syntax` is enabled, which is the default after Bazel 6.0. *Note:* Prior to Bazel 6.0, when this attribute is serialized as part of `bazel query --output=proto` (or `--output=xml`), the leading slashes are omitted. For instance, `//pkg/foo/...` will output as `\"pkg/foo/...\"`. This behavior is fixed when `--incompatible_package_group_includes_double_slash` is enabled, which is the default after Bazel 6.0. | +| `includes` | List of [labels](/concepts/labels); default is `[]` Other package groups that are included in this one. 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 — if package group `a` includes package group `b`, and `b` includes package group `c`, then every package in `c` will also be a member of `a`. When used together with negated package specifications, note that the set of packages for each group is first computed independently and the results are then unioned together. This means that negated specifications in one group have no effect on the specifications in another group. | + +### Examples + +The following `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"], +) +``` + +## exports_files + +``` +exports_files([label, ...], visibility, licenses) +``` + +`exports_files()` specifies a list of files belonging to +this package that are exported to other packages. + +The BUILD file for a package may only refer directly to source files belonging +to another package if they are explicitly exported with an +`exports_files()` statement. Read more about +[visibility of files](/concepts/visibility#source-file-target-visibility). + +As a legacy behaviour, also files mentioned as input to a rule are exported +with the default visibility until the flag +[`--incompatible_no_implicit_file_export`](https://github.com/bazelbuild/bazel/issues/10225) +is flipped. However, this behavior should not be relied upon and actively +migrated away from. + +### Arguments + +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](common-definitions#common.licenses) +can also be specified. + +### Example + +The following example exports `golden.txt`, a +text file from the `test_data` package, so that other +packages may use it, for example, in the `data` attribute +of tests. + +``` +# from //test_data/BUILD + +exports_files(["golden.txt"]) +``` + +## glob + +``` +glob(include, exclude=[], exclude_directories=1, allow_empty=True) +``` + +Glob is a helper function that finds all files that match certain path patterns, +and returns a new, mutable, sorted list of their paths. Glob only searches files +in its own package, and looks only for source files (not generated files nor +other targets). + +A source file's Label is included in the result if the file's package-relative +path matches any of the `include` patterns and none of the +`exclude` patterns. + +The `include` and `exclude` lists contain path patterns +that are relative to the current package. Every pattern may consist of one or +more path segments. As usual with Unix paths, these segments are separated by +`/`. The segments in the pattern are matched against the segments of +the path. Segments may contain the `*` wildcard: this matches +any substring in the path segment (even the empty substring), excluding the +directory separator `/`. This wildcard can be used multiple times +within one path segment. Additionally, the `**` wildcard can match +zero or more complete path segments, but it must be declared as a standalone +path segment. + +Examples: + +* `foo/bar.txt` matches exactly the `foo/bar.txt` file + in this package (unless `foo/` is a subpackage) +* `foo/*.txt` matches every file in the `foo/` directory + if the file ends with `.txt` (unless `foo/` is a + subpackage) +* `foo/a*.htm*` matches every file in the `foo/` + directory that starts with `a`, then has an arbitrary string (could + be empty), then has `.htm`, and ends with another arbitrary string + (unless `foo/` is a subpackage); such as `foo/axx.htm` + and `foo/a.html` or `foo/axxx.html` +* `foo/*` matches every file in the `foo/` directory, + (unless `foo/` is a subpackage); it does not match `foo` + directory itself even if `exclude_directories` is set to + 0 +* `foo/**` matches every file in every non-subpackage subdirectory + under package's first level subdirectory `foo/`; if + `exclude_directories` is set to 0, `foo` + directory itself also matches the pattern; in this case, `**` is + considered to match zero path segments +* `**/a.txt` matches `a.txt` files in this package's + directory plus non-subpackage subdirectories. +* `**/bar/**/*.txt` matches every `.txt` file in every + non-subpackage subdirectory of this package, if at least one directory on the + resulting path is called `bar`, such as + `xxx/bar/yyy/zzz/a.txt` or `bar/a.txt` (remember that + `**` also matches zero segments) or `bar/zzz/a.txt` +* `**` matches every file in every non-subpackage subdirectory of + this package +* `foo**/a.txt` is an invalid pattern, because `**` must + stand on its own as a segment +* `foo/` is an invalid pattern, because the second segment defined + after `/` is an empty string + +If the `exclude_directories` argument is enabled (set to 1), files of +type directory will be omitted from the results (default 1). + +If the `allow_empty` argument is set to `False`, the +`glob` function will error-out if the result would otherwise be the +empty list. + +There are several important limitations and caveats: + +1. Since `glob()` runs during BUILD file evaluation, + `glob()` matches files only in your source tree, never + generated files. If you are building a target that requires both + source and generated files, you must append an explicit list of generated + files to the glob. See the [example](#glob_example) + below with `:mylib` and `:gen_java_srcs`. +2. If a rule has the same name as a matched source file, the rule will + "shadow" the file. + + To understand this, remember that `glob()` returns a list of + paths, so using `glob()` in other rules' attribute (e.g. + `srcs = glob(["*.cc"])`) has the same effect as listing the + matched paths explicitly. If for example `glob()` yields + `["Foo.java", "bar/Baz.java"]` but there's also a rule in the + package called "Foo.java" (which is allowed, though Bazel warns about it), + then the consumer of the `glob()` will use the "Foo.java" rule + (its outputs) instead of the "Foo.java" file. See + [GitHub + issue #10395](https://github.com/bazelbuild/bazel/issues/10395#issuecomment-583714657) for more details. +3. Globs may match files in subdirectories. And subdirectory names + may be wildcarded. However... +4. Labels are not allowed to cross the package boundary and glob does + not match files in subpackages. + + For example, the glob expression `**/*.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` or it was marked as deleted using the + [--deleted_packages](/docs/user-manual#flag--deleted_packages) + flag. +5. The restriction above applies to all glob expressions, + no matter which wildcards they use. +6. A hidden file with filename starting with `.` is completely matched by + both the `**` and the `*` wildcards. If you want to match a hidden file + with a compound pattern, your pattern needs to begin with a `.`. For example, + `*` and `.*.txt` will match `.foo.txt`, but `*.txt` + will not. + Hidden directories are also matched in the same manner. Hidden directories + may include files that are not required as inputs, and can increase the + number of unnecessarily globbed files and memory consumption. To exclude + hidden directories, add them to the "exclude" list argument. +7. The "\*\*" wildcard has one corner case: the pattern + `"**"` doesn't match the package's directory path. That is to + say, `glob(["**"], exclude_directories = 0)` matches all files + and directories transitively strictly under the current package's directory + (but of course not going into directories of subpackages - see the previous + note about that). + +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. + +When writing build rules you can enumerate the elements of the glob. This +enables generating individual rules for every input, for example. See the +[expanded glob example](#expanded_glob_example) section below. + +### Glob Examples + +Create a Java library built from all java files in this directory, +and all files generated by the `:gen_java_srcs` rule. + +``` +java_library( + name = "mylib", + srcs = glob(["*.java"]) + [":gen_java_srcs"], + deps = "...", +) + +genrule( + name = "gen_java_srcs", + outs = [ + "Foo.java", + "Bar.java", + ], + ... +) +``` + +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 (\*\*). + +``` +sh_test( + name = "mytest", + srcs = ["mytest.sh"], + data = glob( + ["testdata/*.txt"], + exclude = ["testdata/experimental.txt"], + ), +) +``` + +### Recursive Glob Examples + +Make the test depend on all txt files in the testdata directory and any +of its subdirectories (and their subdirectories, and so on). +Subdirectories containing a BUILD file are ignored. (See limitations +and caveats above.) + +``` +sh_test( + name = "mytest", + srcs = ["mytest.sh"], + data = glob(["testdata/**/*.txt"]), +) +``` + +Create a library built from all java files in this directory and all +subdirectories except those whose path includes a directory named testing. +**This pattern should be avoided if possible, as it can reduce build +incrementality and therefore increase build times.** + +``` +java_library( + name = "mylib", + srcs = glob( + ["**/*.java"], + exclude = ["**/testing/**"], + ), +) +``` + +### Expanded Glob Examples + +Create an individual genrule for \*\_test.cc in the current directory +that counts the number of lines in the file. + +``` +# Conveniently, the build language supports list comprehensions. +[genrule( + name = "count_lines_" + f[:-3], # strip ".cc" + srcs = [f], + outs = ["%s-linecount.txt" % f[:-3]], + cmd = "wc -l $< >$@", + ) for f in glob(["*_test.cc"])] +``` + +If the BUILD file above is in package //foo and the package contains three +matching files, a_test.cc, b_test.cc and c_test.cc then running +`bazel query '//foo:all'` will list all rules that were generated: + +``` +$ bazel query '//foo:all' | sort +//foo:count_lines_a_test +//foo:count_lines_b_test +//foo:count_lines_c_test +``` + +## select + +``` +select( + {conditionA: valuesA, conditionB: valuesB, ...}, + no_match_error = "custom message" +) +``` + +`select()` is the helper function that makes a rule attribute +[configurable](common-definitions#configurable-attributes). +It can replace the right-hand side of +*almost* +any attribute assignment so its value depends on command-line Bazel flags. +You can use this, for example, to define platform-specific dependencies or to +embed different resources depending on whether a rule is built in "developer" +vs. "release" mode. + +Basic use is as follows: + +``` +sh_binary( + name = "mytarget", + srcs = select({ + ":conditionA": ["mytarget_a.sh"], + ":conditionB": ["mytarget_b.sh"], + "//conditions:default": ["mytarget_default.sh"] + }) +) +``` + +This makes the `srcs` attribute of +a `sh_binary` configurable by replacing its normal label +list assignment with a `select` call that maps +configuration conditions to matching values. Each condition is a label +reference to +a `config_setting` or +`constraint_value`, +which "matches" if the target's configuration matches an expected set of +values. The value of `mytarget#srcs` then becomes whichever +label list matches the current invocation. + +Notes: + +* Exactly one condition is selected on any invocation. +* If multiple conditions match and one is a specialization of the others, + the specialization takes precedence. Condition B is considered a + specialization of condition A if B has all the same flags and constraint + values as A plus some additional flags or constraint values. This also + means that specialization resolution is not designed to create an ordering as + demonstrated in Example 2 below. +* If multiple conditions match and one is not a specialization of all the + others, Bazel fails with an error, unless all conditions resolve to the same value. +* The special pseudo-label `//conditions:default` is + considered to match if no other condition matches. If this condition + is left out, some other rule must match to avoid an error. +* `select` can be embedded *inside* a larger + attribute assignment. So `srcs = ["common.sh"] + + select({ ":conditionA": ["myrule_a.sh"], ...})` and `srcs = select({ ":conditionA": ["a.sh"]}) + select({ ":conditionB": + ["b.sh"]})` are valid expressions. +* `select` works with most, but not all, attributes. Incompatible + attributes are marked `nonconfigurable` in their documentation. + + ## subpackages + + ``` + subpackages(include, exclude=[], allow_empty=True) + ``` + + `subpackages()` is a helper function, similar to `glob()` + that lists subpackages instead of files and directories. It uses the same + path patterns as `glob()` and can match any subpackage that is a + direct descendant of the currently loading BUILD file. See [glob](#glob) for a detailed explanation and examples of include and + exclude patterns. + + The resulting list of subpackages returned is in sorted order and contains + paths relative to the current loading package that match the given patterns in + `include` and not those in `exclude`. + + ### Example + + The following example lists all the direct subpackages for the package `foo/BUILD` + + ``` + # The following BUILD files exist: + # foo/BUILD + # foo/bar/baz/BUILD + # foo/bar/but/bad/BUILD + # foo/sub/BUILD + # foo/sub/deeper/BUILD + # + # In foo/BUILD a call to + subs1 = subpackages(include = ["**"]) + + # results in subs1 == ["sub", "bar/baz", "bar/but/bad"] + # + # 'sub/deeper' is not included because it is a subpackage of 'foo/sub' not of + # 'foo' + + subs2 = subpackages(include = ["bar/*"]) + # results in subs2 = ["bar/baz"] + # + # Since 'bar' is not a subpackage itself, this looks for any subpackages under + # all first level subdirectories of 'bar'. + + subs3 = subpackages(include = ["bar/**"]) + # results in subs3 = ["bar/baz", "bar/but/bad"] + # + # Since bar is not a subpackage itself, this looks for any subpackages which are + # (1) under all subdirectories of 'bar' which can be at any level, (2) not a + # subpackage of another subpackages. + + subs4 = subpackages(include = ["sub"]) + subs5 = subpackages(include = ["sub/*"]) + subs6 = subpackages(include = ["sub/**"]) + # results in subs4 and subs6 being ["sub"] + # results in subs5 = []. + # + # In subs4, expression "sub" checks whether 'foo/sub' is a package (i.e. is a + # subpackage of 'foo'). + # In subs5, "sub/*" looks for subpackages under directory 'foo/sub'. Since + # 'foo/sub' is already a subpackage itself, the subdirectories will not be + # traversed anymore. + # In subs6, 'foo/sub' is a subpackage itself and matches pattern "sub/**", so it + # is returned. But the subdirectories of 'foo/sub' will not be traversed + # anymore. + ``` + + In general it is preferred that instead of calling this function directly + that users use the 'subpackages' module of + [skylib](https://github.com/bazelbuild/bazel-skylib). \ No newline at end of file diff --git a/versions/8.6.0/reference/be/general.mdx b/versions/8.6.0/reference/be/general.mdx new file mode 100644 index 00000000..8840693c --- /dev/null +++ b/versions/8.6.0/reference/be/general.mdx @@ -0,0 +1,576 @@ +--- +title: 'General Rules' +--- + +## Rules + +* [alias](#alias) +* [config_setting](#config_setting) +* [filegroup](#filegroup) +* [genquery](#genquery) +* [genrule](#genrule) +* [starlark_doc_extract](#starlark_doc_extract) +* [test_suite](#test_suite) + +## alias + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/Alias.java) + +``` +alias(name, actual, compatible_with, deprecation, features, restricted_to, tags, target_compatible_with, testonly, visibility) +``` + +The `alias` rule creates another name a rule can be referred to as. + +Aliasing only works for "regular" targets. In particular, `package_group` +and `test_suite` cannot be aliased. + +Aliasing may be of help in large repositories where renaming a target would require making +changes to lots of files. You can also use alias rule to store a +[select](/reference/be/functions#select) function call if you want to reuse that logic for +multiple targets. + +The alias rule has its own visibility declaration. In all other respects, it behaves +like the rule it references (e.g. testonly *on the alias* is ignored; the testonly-ness +of the referenced rule is used instead) with some minor exceptions: + +* Tests are not run if their alias is mentioned on the command line. To define an alias + that runs the referenced test, use a [`test_suite`](#test_suite) + rule with a single target in its [`tests`](#test_suite.tests) + attribute. +* When defining environment groups, the aliases to `environment` rules are not + supported. They are not supported in the `--target_environment` command line + option, either. + +#### Examples + +``` +filegroup( + name = "data", + srcs = ["data.txt"], +) + +alias( + name = "other", + actual = ":data", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `actual` | [Label](/concepts/labels); required The target this alias refers to. It does not need to be a rule, it can also be an input file. | + +## config_setting + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/config/ConfigRuleClasses.java) + +``` +config_setting(name, constraint_values, define_values, deprecation, distribs, features, flag_values, licenses, tags, testonly, values, visibility) +``` + +Matches an expected configuration state (expressed as build flags or platform constraints) for +the purpose of triggering configurable attributes. See [select](/reference/be/functions#select) for +how to consume this rule and [Configurable attributes](/reference/be/common-definitions#configurable-attributes) for an overview of the general feature. + +#### Examples + +The following matches any build that sets `--compilation_mode=opt` or +`-c opt` (either explicitly at the command line or implicitly from .bazelrc files): + +``` + config_setting( + name = "simple", + values = {"compilation_mode": "opt"} + ) +``` + +The following matches any build that targets ARM and applies the custom define +`FOO=bar` (for instance, `bazel build --cpu=arm --define FOO=bar ...`): + +``` + config_setting( + name = "two_conditions", + values = { + "cpu": "arm", + "define": "FOO=bar" + } + ) +``` + +The following matches any build that sets +[user-defined flag](https://bazel.build/rules/config#user-defined-build-settings) +`--//custom_flags:foo=1` (either explicitly at the command line or implicitly from +.bazelrc files): + +``` + config_setting( + name = "my_custom_flag_is_set", + flag_values = { "//custom_flags:foo": "1" }, + ) +``` + +The following matches any build that targets a platform with an x86_64 architecture and glibc +version 2.25, assuming the existence of a `constraint_value` with label +`//example:glibc_2_25`. Note that a platform still matches if it defines additional +constraint values beyond these two. + +``` + config_setting( + name = "64bit_glibc_2_25", + constraint_values = [ + "@platforms//cpu:x86_64", + "//example:glibc_2_25", + ] + ) +``` + +In all these cases, it's possible for the configuration to change within the build, for example if +a target needs to be built for a different platform than its dep. This means that even when a +`config_setting` doesn't match the top-level command-line flags, it may still match +some build targets. + +#### Notes + +* See [select](/reference/be/functions#select) for what happens when multiple + `config_setting`s match the current configuration state. +* For flags that support shorthand forms (e.g. `--compilation_mode` vs. + `-c`), `values` definitions must use the full form. These automatically + match invocations using either form. +* If a flag takes multiple values (like `--copt=-Da --copt=-Db` or a list-typed + [Starlark flag](https://bazel.build/rules/config#user-defined-build-settings)), `values = { "flag": "a" }` matches if `"a"` is + present *anywhere* in the actual list. + + `values = { "myflag": "a,b" }` works the same way: this matches + `--myflag=a --myflag=b`, `--myflag=a --myflag=b --myflag=c`, + `--myflag=a,b`, and `--myflag=c,b,a`. Exact semantics vary between + flags. For example, `--copt` doesn't support multiple values *in the same + instance*: `--copt=a,b` produces `["a,b"]` while `--copt=a + --copt=b` produces `["a", "b"]` (so `values = { "copt": "a,b" }` + matches the former but not the latter). But `--ios_multi_cpus` (for Apple rules) + *does*: `-ios_multi_cpus=a,b` and `ios_multi_cpus=a --ios_multi_cpus=b` both produce `["a", "b"]`. Check flag definitions and test your + conditions carefully to verify exact expectations. +* If you need to define conditions that aren't modeled by built-in build flags, use + [Starlark-defined flags](https://bazel.build/rules/config#user-defined-build-settings). You can also use `--define`, but this offers weaker + support and is not recommended. See + [here](/reference/be/common-definitions#configurable-attributes) for more discussion. +* Avoid repeating identical `config_setting` definitions in different packages. + Instead, reference a common `config_setting` that defined in a canonical package. +* [`values`](general#config_setting.values), + [`define_values`](general#config_setting.define_values), and + [`constraint_values`](general#config_setting.constraint_values) + can be used in any combination in the same `config_setting` but at least one must + be set for any given `config_setting`. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `constraint_values` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` The minimum set of `constraint_values` that the target platform must specify in order to match this `config_setting`. (The execution platform is not considered here.) Any additional constraint values that the platform has are ignored. See [Configurable Build Attributes](https://bazel.build/docs/configurable-attributes#platforms) for details. If two `config_setting`s match in the same `select` and one has all the same flags and `constraint_setting`s as the other plus additional ones, the one with more settings is chosen. This is known as "specialization". For example, a `config_setting` matching `x86` and `Linux` specializes a `config_setting` matching `x86`. If two `config_setting`s match and both have `constraint_value`s not present in the other, this is an error. | +| `define_values` | Dictionary: String -> String; [nonconfigurable](common-definitions#configurable-attributes); default is `{}` The same as [`values`](/reference/be/general#config_setting.values) but specifically for the `--define` flag. `--define` is special because its syntax (`--define KEY=VAL`) means `KEY=VAL` is a *value* from a Bazel flag perspective. That means: ``` config_setting( name = "a_and_b", values = { "define": "a=1", "define": "b=2", }) ``` doesn't work because the same key (`define`) appears twice in the dictionary. This attribute solves that problem: ``` config_setting( name = "a_and_b", define_values = { "a": "1", "b": "2", }) ``` correctly matches `bazel build //foo --define a=1 --define b=2`. `--define` can still appear in [`values`](/reference/be/general#config_setting.values) with normal flag syntax, and can be mixed freely with this attribute as long as dictionary keys remain distinct. | +| `flag_values` | Dictionary: [label](/concepts/labels) -> String; [nonconfigurable](common-definitions#configurable-attributes); default is `{}` The same as [`values`](/reference/be/general#config_setting.values) but for [user-defined build flags](https://bazel.build/rules/config#user-defined-build-settings). This is a distinct attribute because user-defined flags are referenced as labels while built-in flags are referenced as arbitrary strings. | +| `values` | Dictionary: String -> String; [nonconfigurable](common-definitions#configurable-attributes); default is `{}` The set of configuration values that match this rule (expressed as build flags) This rule inherits the configuration of the configured target that references it in a `select` statement. It is considered to "match" a Bazel invocation if, for every entry in the dictionary, its configuration matches the entry's expected value. For example `values = {"compilation_mode": "opt"}` matches the invocations `bazel build --compilation_mode=opt ...` and `bazel build -c opt ...` on target-configured rules. For convenience's sake, configuration values are specified as build flags (without the preceding `"--"`). But keep in mind that the two are not the same. This is because targets can be built in multiple configurations within the same build. For example, an exec configuration's "cpu" matches the value of `--host_cpu`, not `--cpu`. So different instances of the same `config_setting` may match the same invocation differently depending on the configuration of the rule using them. If a flag is not explicitly set at the command line, its default value is used. If a key appears multiple times in the dictionary, only the last instance is used. If a key references a flag that can be set multiple times on the command line (e.g. `bazel build --copt=foo --copt=bar --copt=baz ...`), a match occurs if *any* of those settings match. | + +## filegroup + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/filegroup/FilegroupRule.java) + +``` +filegroup(name, srcs, data, compatible_with, deprecation, distribs, features, licenses, output_group, restricted_to, tags, target_compatible_with, testonly, visibility) +``` + +Use `filegroup` to gather the outputs of a set of targets under a single +label. + +`filegroup` is not a substitute for listing targets on the command line or +in an attribute of another rule, because targets have many properties other than their +outputs, which are not collected in the same way. However, it's still useful in quite +a few cases, for example, in the `srcs` attribute of a genrule, or +the `data` attribute of a \*\_binary rule. + +Using `filegroup` is encouraged instead of referencing directories directly. +Directly referencing directories is discouraged because the build system does not have +full knowledge of all files below the directory, so it may not rebuild when these files change. +When combined with [glob](/reference/be/functions#glob), `filegroup` can ensure that all +files are explicitly known to the build system. + +#### Examples + +To create a `filegroup` consisting of two source files, do + +``` +filegroup( + name = "mygroup", + srcs = [ + "a_file.txt", + "//a/library:target", + "//a/binary:target", + ], +) +``` + +Or, use a `glob` to fully crawl 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", + ], +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of targets that are members of the file group. It is common to use the result of a [glob](/reference/be/functions#glob) expression for the value of the `srcs` attribute. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this rule at runtime. Targets named in the `data` attribute will be added to the `runfiles` of this `filegroup` rule. When the `filegroup` is referenced in the `data` attribute of another rule its `runfiles` will be added to the `runfiles` of the depending rule. See the [data dependencies](/concepts/dependencies#data-dependencies) section and [general documentation of `data`](/reference/be/common-definitions#common.data) for more information about how to depend on and use data files. | +| `output_group` | String; default is `""` The output group from which to gather artifacts from sources. If this attribute is specified, artifacts from the specified output group of the dependencies will be exported instead of the default output group. An "output group" is a category of output artifacts of a target, specified in that rule's implementation. | + +## genquery + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/genquery/GenQueryRule.java) + +``` +genquery(name, deps, data, compatible_with, compressed_output, deprecation, distribs, exec_compatible_with, exec_properties, expression, features, licenses, opts, restricted_to, scope, strict, tags, target_compatible_with, testonly, visibility) +``` + +`genquery()` runs a query specified in the +[Bazel query language](/reference/query) and dumps the result +into a file. + +In order to keep the build consistent, the query is allowed only to visit +the transitive closure of the targets specified in the `scope` +attribute. Queries violating this rule will fail during execution if +`strict` is unspecified or true (if `strict` is false, +the out of scope targets will simply be skipped with a warning). The +easiest way to make sure this does not happen is to mention the same labels +in the scope as in the query expression. + +The only difference between the queries allowed here and on the command +line is that queries containing wildcard target specifications (e.g. +`//pkg:*` or `//pkg:all`) are not allowed here. +The reasons for this are two-fold: first, because `genquery` has +to specify a scope to prevent targets outside the transitive closure of the +query to influence its output; and, second, because `BUILD` files +do not support wildcard dependencies (e.g. `deps=["//a/..."]` +is not allowed). + +The genquery's output is ordered lexicographically in order to enforce deterministic output, +with the exception of `--output=graph|minrank|maxrank` or when `somepath` +is used as the top-level function. + +The name of the output file is the name of the rule. + +#### Examples + +This example writes the list of the labels in the transitive closure of the +specified target to a file. + +``` +genquery( + name = "kiwi-deps", + expression = "deps(//kiwi:kiwi_lib)", + scope = ["//kiwi:kiwi_lib"], +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `compressed_output` | Boolean; default is `False` If `True`, query output is written in GZIP file format. This setting can be used to avoid spikes in Bazel's memory use when the query output is expected to be large. Bazel already internally compresses query outputs greater than 220 bytes regardless of the value of this setting, so setting this to `True` may not reduce retained heap. However, it allows Bazel to skip *decompression* when writing the output file, which can be memory-intensive. | +| `expression` | String; required The query to be executed. In contrast to the command line and other places in BUILD files, labels here are resolved relative to the root directory of the workspace. For example, the label `:b` in this attribute in the file `a/BUILD` will refer to the target `//:b`. | +| `opts` | List of strings; default is `[]` The options that are passed to the query engine. These correspond to the command line options that can be passed to `bazel query`. Some query options are not allowed here: `--keep_going`, `--query_file`, `--universe_scope`, `--order_results` and `--order_output`. Options not specified here will have their default values just like on the command line of `bazel query`. | +| `scope` | List of [labels](/concepts/labels); required The scope of the query. The query is not allowed to touch targets outside the transitive closure of these targets. | +| `strict` | Boolean; default is `True` If true, targets whose queries escape the transitive closure of their scopes will fail to build. If false, Bazel will print a warning and skip whatever query path led it outside of the scope, while completing the rest of the query. | + +## genrule + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/bazel/rules/genrule/BazelGenRuleRule.java) + +``` +genrule(name, srcs, outs, cmd, cmd_bash, cmd_bat, cmd_ps, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, executable, features, licenses, local, message, output_licenses, output_to_bindir, restricted_to, tags, target_compatible_with, testonly, toolchains, tools, visibility) +``` + +A `genrule` generates one or more files using a user-defined Bash command. + +Genrules are generic build rules that you can use if there's no specific rule for the task. +For example, you could run a Bash one-liner. If however you need to compile C++ files, stick +to the existing `cc_*` rules, because all the heavy lifting has already been done +for you. + +Note that genrule requires a shell to interpret the command argument. +It is also easy to reference arbitrary programs available on the PATH, however this makes the +command non-hermetic and may not be reproducible. +If you only need to run a single tool, consider using +[run_binary](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/run_binary_doc.md) +instead. + +Like every other action, the action created by genrules should not assume anything about their +working directory; all Bazel guarantees is that their declared inputs will be available at the +path that `$(location)` returns for their label. For example, if the action is run in a +sandbox or remotely, the implementation of the sandbox or the remote execution will determine the +working directory. If run directly (using the `standalone` strategy), the working +directory will be the execution root, i.e. the result of `bazel info execution_root`. + +Do not use a genrule for running tests. There are special dispensations for tests and test +results, including caching policies and environment variables. Tests generally need to be run +after the build is complete and on the target architecture, whereas genrules are executed during +the build and on the exec architecture (the two may be different). If you need a general purpose +testing rule, use [`sh_test`](/reference/be/shell#sh_test). + +#### Cross-compilation Considerations + +*See [the user manual](/docs/user-manual#configurations) for more info about +cross-compilation.* + +While genrules run during a build, their outputs are often used after the build, for deployment or +testing. Consider the example of compiling C code for a microcontroller: the compiler accepts C +source files and generates code that runs on a microcontroller. The generated code obviously +cannot run on the CPU that was used for building it, but the C compiler (if compiled from source) +itself has to. + +The build system uses the exec configuration to describe the machine(s) on which the build runs +and the target configuration to describe the machine(s) 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 *exec* configuration, and the output is considered to +be for the *target* configuration. It also provides ["Make" variables](/reference/be/make-variables) that genrule commands can pass to the corresponding tools. + +It is intentional that genrule defines no `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. + +#### Special Cases + +*Exec-exec compilation*: in some cases, the build system needs to run genrules such that the +output can also be executed during the build. If for example a genrule builds some custom compiler +which is subsequently used by another genrule, the first one has to produce its output for the +exec configuration, because that's where the compiler will run in the other genrule. In this case, +the build system does the right thing automatically: it builds the `srcs` and +`outs` of the first genrule for the exec configuration instead of the target +configuration. See [the user manual](/docs/user-manual#configurations) for more +info. + +*JDK & C++ Tooling*: to use a tool from the JDK or the C++ compiler suite, the build system +provides a set of variables to use. See ["Make" variable](/reference/be/make-variables) for +details. + +#### Genrule Environment + +The genrule command is executed by a Bash shell that is configured to fail when a command +or a pipeline fails, using `set -e -o pipefail`. + +The build tool executes the Bash command in a sanitized process environment that +defines only core variables such as `PATH`, `PWD`, +`TMPDIR`, and a few others. +To ensure that builds are reproducible, most variables defined in the user's shell +environment are not passed though to the genrule's command. However, Bazel (but not +Blaze) passes through the value of the user's `PATH` environment variable. +Any change to the value of `PATH` will cause Bazel to re-execute the command +on the next build. + +A genrule command should not access the network except to connect processes that are +children of the command itself, though this is not currently enforced. + +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. + +#### General Advice + +* Do ensure that tools run by a genrule are deterministic and hermetic. They should not write + timestamps to their output, and they should use stable ordering for sets and maps, as well as + write only relative file paths to the output, no absolute paths. Not following this rule will + lead to unexpected build behavior (Bazel not rebuilding a genrule you thought it would) and + degrade cache performance. +* Do use `$(location)` extensively, for outputs, tools and sources. Due to the + segregation of output files for different configurations, genrules cannot rely on hard-coded + and/or absolute paths. +* Do write a common Starlark macro in case the same or very similar genrules are used in + multiple places. If the genrule is complex, consider implementing it in a script or as a + Starlark rule. This improves readability as well as testability. +* Do make sure that the exit code correctly indicates success or failure of the genrule. +* Do not write informational messages to stdout or stderr. While useful for debugging, this can + easily become noise; a successful genrule should be silent. On the other hand, a failing genrule + should emit good error messages. +* `$$` evaluates to a `$`, a literal dollar-sign, so in order to invoke a + shell command containing dollar-signs such as `ls $(dirname $x)`, one must escape it + thus: `ls $$(dirname $$x)`. +* Avoid creating symlinks and directories. Bazel doesn't copy over the directory/symlink + structure created by genrules and its dependency checking of directories is unsound. +* When referencing the genrule in other rules, you can use either the genrule's label or the + labels of individual output files. Sometimes the one approach is more readable, sometimes the + other: referencing outputs by name in a consuming rule's `srcs` will avoid + unintentionally picking up other outputs of the genrule, but can be tedious if the genrule + produces many outputs. + +#### Examples + +This example generates `foo.h`. There are no sources, because the command doesn't take +any input. The "binary" run by the command is a perl script in the same package as the genrule. + +``` +genrule( + name = "foo", + srcs = [], + outs = ["foo.h"], + cmd = "./$(location create_foo.pl) > \"$@\"", + tools = ["create_foo.pl"], +) +``` + +The following example shows how to use a [`filegroup`](/reference/be/general#filegroup) and the outputs of another `genrule`. Note that using `$(SRCS)` instead +of explicit `$(location)` directives would also work; this example uses the latter for +sake of demonstration. + +``` +genrule( + name = "concat_all_files", + srcs = [ + "//some:files", # a filegroup with multiple files in it ==> $(locations) + "//other:gen", # a genrule with a single output ==> $(location) + ], + outs = ["concatenated.txt"], + cmd = "cat $(locations //some:files) $(location //other:gen) > $@", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. You may refer to this rule by name in the `srcs` or `deps` section of other `BUILD` rules. If the rule generates source files, you should use the `srcs` attribute. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` A list of inputs for this rule, such as source files to process. *This attributes is not suitable to list tools executed by the `cmd`; use the [`tools`](/reference/be/general#genrule.tools) attribute for them instead.* 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)`, or using `$<` provided it's the only entry in `srcs`. | +| `outs` | List of [filenames](/concepts/build-ref#filename); [nonconfigurable](common-definitions#configurable-attributes); required A list of files generated by this rule. Output files must not cross package boundaries. Output filenames are interpreted as relative to the package. If the `executable` flag is set, `outs` must contain exactly one label. The genrule command is expected to create each output file at a predetermined location. The location is available in `cmd` using [genrule-specific "Make" variables](/reference/be/make-variables#predefined_genrule_variables) (`$@`, `$(OUTS)`, `$(@D)` or `$(RULEDIR)`) or using [`$(location)`](/reference/be/make-variables#predefined_label_variables) substitution. | +| `cmd` | String; default is `""` The command to run. Subject to [`$(location)`](/reference/be/make-variables#predefined_label_variables) and ["Make" variable](/reference/be/make-variables) substitution. 1. First [`$(location)`](/reference/be/make-variables#predefined_label_variables) substitution is applied, replacing all occurrences of `$(location label)` and of `$(locations label)` (and similar constructions using related variables `execpath`, `execpaths`, `rootpath` and `rootpaths`). 2. Next, ["Make" variables](/reference/be/make-variables) are expanded. Note that predefined variables `$(JAVA)`, `$(JAVAC)` and `$(JAVABASE)` expand under the *exec* configuration, so Java invocations that run as part of a build step can correctly load shared libraries and other dependencies. 3. Finally, the resulting command is executed using the Bash shell. If its exit code is non-zero the command is considered to have failed. This is the fallback of `cmd_bash`, `cmd_ps` and `cmd_bat`, if none of them are applicable. | + +If the command line length exceeds the platform limit (64K on Linux/macOS, 8K on Windows), +then genrule will write the command to a script and execute that script to work around. This +applies to all cmd attributes (`cmd`, `cmd_bash`, `cmd_ps`, +`cmd_bat`). + +| `cmd_bash` | String; default is `""` The Bash command to run. This attribute has higher priority than `cmd`. The command is expanded and runs in the exact same way as the `cmd` attribute. | +| `cmd_bat` | String; default is `""` The Batch command to run on Windows. This attribute has higher priority than `cmd` and `cmd_bash`. The command runs in the similar way as the `cmd` attribute, with the following differences: * This attribute only applies on Windows. * The command runs with `cmd.exe /c` with the following default arguments: + `/S` - strip first and last quotes and execute everything else as is. + `/E:ON` - enable extended command set. + `/V:ON` - enable delayed variable expansion + `/D` - ignore AutoRun registry entries. * After [$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make" variable](/reference/be/make-variables) substitution, the paths will be expanded to Windows style paths (with backslash). | +| `cmd_ps` | String; default is `""` The Powershell command to run on Windows. This attribute has higher priority than `cmd`, `cmd_bash` and `cmd_bat`. The command runs in the similar way as the `cmd` attribute, with the following differences: * This attribute only applies on Windows. * The command runs with `powershell.exe /c`. To make Powershell easier to use and less error-prone, we run the following commands to set up the environment before executing Powershell command in genrule. * `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned` - allow running unsigned scripts. * `$errorActionPreference='Stop'` - In case there are multiple commands separated by `;`, the action exits immediately if a Powershell CmdLet fails, but this does **NOT** work for external command. * `$PSDefaultParameterValues['*:Encoding'] = 'utf8'` - change the default encoding from utf-16 to utf-8. | +| `executable` | Boolean; [nonconfigurable](common-definitions#configurable-attributes); default is `False` Declare output to be executable. Setting this flag to True means the output is an executable file and can be run using the `run` command. The genrule must produce exactly one output in this case. If this attribute is set, `run` will try executing the file regardless of its content. Declaring data dependencies for the generated executable is not supported. | +| `local` | Boolean; default is `False` If set to True, this option forces this `genrule` to run using the "local" strategy, which means no remote execution, no sandboxing, no persistent workers. This is equivalent to providing 'local' as a tag (`tags=["local"]`). | +| `message` | String; default is `""` A progress message. A progress message that will be printed as this build step is executed. By default, the message is "Generating *output*" (or something equally bland) but you may provide a more specific one. Use this attribute instead of `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` | Licence type; default is `["none"]` See [`common attributes`](/reference/be/common-definitions#binary.output_licenses) | +| `output_to_bindir` | Boolean; [nonconfigurable](common-definitions#configurable-attributes); default is `False` If set to True, this option causes output files to be written into the `bin` directory instead of the `genfiles` directory. | +| `toolchains` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` The set of targets whose [Make variables](/reference/be/make-variables) this genrule is allowed to access, or the [`toolchain_type`](/docs/toolchains) targets that this genrule will access. Toolchains accessed via `toolchain_type` must also provide a `TemplateVariableInfo` provider, which the target can use to access toolchain details. | +| `tools` | List of [labels](/concepts/labels); default is `[]` A list of *tool* dependencies for this rule. See the definition of [dependencies](/concepts/build-ref#deps) for more information. The build system ensures these prerequisites are built before running the genrule command; they are built using the [*exec* configuration](/contribute/guide#configurations), since these tools are executed as part of the build. The path of an individual `tools` target `//x:y` can be obtained using `$(location //x:y)`. Any `*_binary` or tool to be executed by `cmd` must appear in this list, not in `srcs`, to ensure they are built in the correct configuration. | + +## starlark_doc_extract + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/starlarkdocextract/StarlarkDocExtractRule.java) + +``` +starlark_doc_extract(name, deps, src, data, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, licenses, render_main_repo_name, restricted_to, symbol_names, tags, target_compatible_with, testonly, visibility) +``` + +`starlark_doc_extract()` extracts documentation for rules, functions (including +macros), aspects, and providers defined or re-exported in a given `.bzl` or +`.scl` file. The output of this rule is a `ModuleInfo` binary proto as defined +in +[stardoc_output.proto](https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/stardoc_output.proto) +in the Bazel source tree. + +#### Implicit output targets + +* `name.binaryproto` (the default output): A + `ModuleInfo` binary proto. +* `name.textproto` (only built if explicitly requested): the text + proto version of `name.binaryproto`. + +Warning: the output format of this rule is not guaranteed to be stable. It is intended mainly for +internal use by [Stardoc](https://github.com/bazelbuild/stardoc). + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` A list of targets wrapping the Starlark files which are `load()`-ed by `src`. These targets *should* under normal usage be [`bzl_library`](https://github.com/bazelbuild/bazel-skylib/blob/main/bzl_library.bzl) targets, but the `starlark_doc_extract` rule does not enforce that, and accepts any target which provides Starlark files in its `DefaultInfo`. Note that the wrapped Starlark files must be files in the source tree; Bazel cannot `load()` generated files. | +| `src` | [Label](/concepts/labels); required A Starlark file from which to extract documentation. Note that this must be a file in the source tree; Bazel cannot `load()` generated files. | +| `render_main_repo_name` | Boolean; default is `False` If true, render labels in the main repository in emitted documentation with a repo component (in other words, `//foo:bar.bzl` will be emitted as `@main_repo_name//foo:bar.bzl`). The name to use for the main repository is obtained from `module(name = ...)` in the main repository's `MODULE.bazel` file (if Bzlmod is enabled), or from `workspace(name = ...)` in the main repository's `WORKSPACE` file. This attribute should be set to `False` when generating documentation for Starlark files which are intended to be used only within the same repository, and to `True` when generating documentation for Starlark files which are intended to be used from other repositories. | +| `symbol_names` | List of strings; default is `[]` An optional list of qualified names of exported functions, rules, providers, or aspects (or structs in which they are nested) for which to extract documentation. Here, a *qualified name* means the name under which an entity is made available to a user of the module, including any structs in which the entity is nested for namespacing. `starlark_doc_extract` emits documentation for an entity if and only if 1. each component of the entity's qualified name is public (in other words, the first character of each component of the qualified name is alphabetic, not `"_"`); *and* 2. 1. *either* the `symbol_names` list is empty (which is the default case), *or* 2. the entity's qualified name, or the qualified name of a struct in which the entity is nested, is in the `symbol_names` list. | + +## test_suite + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/test/TestSuiteRule.java) + +``` +test_suite(name, compatible_with, deprecation, distribs, features, licenses, restricted_to, tags, target_compatible_with, 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." The `bazel test` command respects this sort +of organization: For an invocation like `bazel test //some/test:suite`, Bazel first +enumerates all test targets transitively included by the `//some/test:suite` target (we +call this "test_suite expansion"), then Bazel builds and tests those targets. + +#### Examples + +A test suite to run all of the small tests in the current package. + +``` +test_suite( + name = "small_tests", + tags = ["small"], +) +``` + +A test suite that runs a specified set of tests: + +``` +test_suite( + name = "smoke_tests", + tests = [ + "system_unittest", + "public_api_unittest", + ], +) +``` + +A test suite to run all tests in the current package which are not flaky. + +``` +test_suite( + name = "non_flaky_test", + tags = ["-flaky"], +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `tags` | List of strings; [nonconfigurable](common-definitions#configurable-attributes); default is `[]` List of text tags such as "small" or "database" or "-flaky". Tags may be any valid string. Tags which begin with a "-" character are considered negative tags. The preceding "-" character is not considered part of the tag, so a suite tag of "-small" matches a test's "small" size. All other tags are considered positive tags. Optionally, to make positive tags more explicit, tags may also begin with the "+" character, which will not be evaluated as part of the text of the tag. It merely makes the positive and negative distinction easier to read. Only test rules that match **all** of the positive tags and **none** of the negative tags will be included in the test suite. Note that this does not mean that error checking for dependencies on tests that are filtered out is skipped; the dependencies on skipped tests still need to be legal (e.g. not blocked by visibility constraints). The `manual` tag keyword is treated differently than the above by the "test_suite expansion" performed by the `bazel test` command on invocations involving wildcard [target patterns](https://bazel.build/docs/build#specifying-build-targets). There, `test_suite` targets tagged "manual" are filtered out (and thus not expanded). This behavior is consistent with how `bazel build` and `bazel test` handle wildcard target patterns in general. Note that this is explicitly different from how `bazel query 'tests(E)'` behaves, as suites are always expanded by the `tests` query function, regardless of the `manual` tag. Note that a test's `size` is considered a tag for the purpose of filtering. If you need a `test_suite` that contains tests with mutually exclusive tags (e.g. all small and medium tests), you'll have to create three `test_suite` rules: one for all small tests, one for all medium tests, and one that includes the previous two. | +| `tests` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` A list of test suites and test targets of any language. Any `*_test` is accepted here, independent of the language. No `*_binary` targets are accepted however, even if they happen to run a test. Filtering by the specified `tags` is only done for tests listed directly in this attribute. If this attribute contains `test_suite`s, the tests inside those will not be filtered by this `test_suite` (they are considered to be filtered already). If the `tests` attribute is unspecified or empty, the rule will default to including all test rules in the current BUILD file that are not tagged as `manual`. These rules are still subject to `tag` filtering. | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/java.mdx b/versions/8.6.0/reference/be/java.mdx new file mode 100644 index 00000000..9fe6ef85 --- /dev/null +++ b/versions/8.6.0/reference/be/java.mdx @@ -0,0 +1,490 @@ +--- +title: 'Java Rules' +--- + +## Rules + +* [java_binary](#java_binary) +* [java_import](#java_import) +* [java_library](#java_library) +* [java_test](#java_test) +* [java_package_configuration](#java_package_configuration) +* [java_plugin](#java_plugin) +* [java_runtime](#java_runtime) +* [java_toolchain](#java_toolchain) + +## java_binary + +[View rule sourceopen_in_new](@rules_java//java/bazel/rules/bazel_java_binary.bzl) + +``` +java_binary(name, deps, srcs, data, resources, add_exports, add_opens, args, bootclasspath, classpath_resources, compatible_with, create_executable, deploy_env, deploy_manifest_lines, deprecation, distribs, env, exec_compatible_with, exec_properties, features, javacopts, jvm_flags, launcher, licenses, main_class, neverlink, output_licenses, plugins, resource_strip_prefix, restricted_to, runtime_deps, stamp, tags, target_compatible_with, testonly, toolchains, use_launcher, 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. When running the wrapper shell script, any nonempty +`JAVABIN` environment variable will take precedence over the version specified via +Bazel's `--java_runtime_version` flag. + +The wrapper script accepts several unique flags. Refer to +`java_stub_template.txt` +for a list of configurable flags and environment variables accepted by the wrapper. + +#### Implicit output targets + +* `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 `<name>_deploy.jar` target for your rule + creates a self-contained 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 to `java -jar` because it + also passes the [JVM flags](#java_binary-jvm_flags) and the options + to load native 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 dependencies. These are automatically loaded + into the JVM at runtime. + + If your target specifies a [launcher](#java_binary.launcher) + attribute, then instead of being a normal JAR file, the \_deploy.jar will be a + native binary. This will contain the launcher plus any native (C++) dependencies of + your rule, all linked into a static binary. The actual jar file's bytes will be + appended to that native binary, creating a single binary blob containing both the + executable and the Java code. You can execute the resulting jar file directly + like you would execute any native binary. +* `name_deploy-src.jar`: An archive containing the sources + collected from the transitive closure of the target. These will match the classes in the + `deploy.jar` except where jars have no matching source jar. + +It is good practice to use the name of the source file that is the main entry point of the +application (minus the extension). For example, if your entry point is called +`Main.java`, then your name could be `Main`. + +A `deps` attribute is not allowed in a `java_binary` rule without +[`srcs`](#java_binary-srcs); such a rule requires a +[`main_class`](#java_binary-main_class) provided by +[`runtime_deps`](#java_binary-runtime_deps). + +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 +) +``` + +Do this instead: + +``` +java_binary( + name = "DoThisInstead", + srcs = [ + ..., + ":generating_rule", + ], +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries to be linked in to the target. See general comments about `deps` at [Typical attributes defined by most build rules](common-definitions#typical-attributes). | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of source files that are processed to create the target. This attribute is almost always required; see exceptions below. Source files of type `.java` are compiled. In case of generated `.java` files it is generally advisable to put the generating rule's name here instead of the name of the file itself. This not only improves readability but makes the rule 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. You should not list the generating rule in `deps` because it is a no-op. Source files of type `.srcjar` are unpacked and compiled. (This is useful if you need to generate a set of `.java` files with a genrule.) Rules: if the rule (typically `genrule` or `filegroup`) generates any of the files listed above, they will be used the same way as described for source files. This argument is almost always required, except if a [`main_class`](#java_binary.main_class) attribute specifies a class on the runtime classpath or you specify the `runtime_deps` argument. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this library at runtime. See general comments about `data` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). | +| `resources` | List of [labels](/concepts/labels); default is `[]` A list of data files to include in a Java jar. Resources may be source files or generated files. If resources are specified, they will be bundled in the jar along with the usual `.class` files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven's [standard directory layout](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html), (a "src" directory followed by a "resources" directory grandchild). If that is not found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for example, if a resource is at `<workspace root>/x/java/y/java/z`, the path of the resource will be `y/java/z`. This heuristic cannot be overridden, however, the `resource_strip_prefix` attribute can be used to specify a specific alternative directory for resource files. | +| `add_exports` | List of strings; default is `[]` Allow this library to access the given `module` or `package`. This corresponds to the javac and JVM --add-exports= flags. | +| `add_opens` | List of strings; default is `[]` Allow this library to reflectively access the given `module` or `package`. This corresponds to the javac and JVM --add-opens= flags. | +| `bootclasspath` | [Label](/concepts/labels); default is `None` Restricted API, do not use! | +| `classpath_resources` | List of [labels](/concepts/labels); default is `[]` *DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY)* A list of resources that must be located at the root of the java tree. This attribute's only purpose is to support third-party libraries that require 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` | Boolean; default is `True` Deprecated, use `java_single_jar` instead. | +| `deploy_env` | List of [labels](/concepts/labels); default is `[]` 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`. Setting this attribute excludes all dependencies from the runtime classpath (and the deploy jar) of this binary that are shared between this binary and the targets specified in `deploy_env`. | +| `deploy_manifest_lines` | List of strings; default is `[]` A list of lines to add to the `META-INF/manifest.mf` file generated for the `*_deploy.jar` target. The contents of this attribute are *not* subject to ["Make variable"](make-variables) substitution. | +| `javacopts` | List of strings; default is `[]` Extra compiler options for this binary. Subject to ["Make variable"](make-variables) substitution and [Bourne shell tokenization](common-definitions#sh-tokenization). These compiler options are passed to javac after the global compiler options. | +| `jvm_flags` | List of strings; default is `[]` A list of flags to embed in the wrapper script generated for running this binary. Subject to [$(location)](/reference/be/make-variables#location) and ["Make variable"](make-variables) substitution, and [Bourne shell tokenization](common-definitions#sh-tokenization). The wrapper script for a Java binary includes a CLASSPATH definition (to find all the dependent jars) and invokes the right Java interpreter. The command line generated by the wrapper script includes the name of the main class followed by a `"$@"` 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. Note that this attribute has *no effect* on `*_deploy.jar` outputs. | +| `launcher` | [Label](/concepts/labels); default is `None` Specify a binary that will be used to run your Java program instead of the normal `bin/java` program included with the JDK. The target must be a `cc_binary`. Any `cc_binary` that implements the [Java Invocation API](http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/invocation.html) can be specified as a value for this attribute. By default, Bazel will use the normal JDK launcher (bin/java or java.exe). The related [`--java_launcher`](/docs/user-manual#flag--java_launcher) Bazel flag affects only those `java_binary` and `java_test` targets that have *not* specified a `launcher` attribute. Note that your native (C++, SWIG, JNI) dependencies will be built differently depending on whether you are using the JDK launcher or another launcher: * If you are using the normal JDK launcher (the default), native dependencies are built as a shared library named `{name}_nativedeps.so`, where `{name}` is the `name` attribute of this java_binary rule. Unused code is *not* removed by the linker in this configuration. * If you are using any other launcher, native (C++) dependencies are statically linked into a binary named `{name}_nativedeps`, where `{name}` is the `name` attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless that `cc_library` target specifies `alwayslink = True`. When using any launcher other than the default JDK launcher, the format of the `*_deploy.jar` output changes. See the main [java_binary](#java_binary) docs for details. | +| `main_class` | String; default is `""` Name of class with `main()` method to use as entry point. If a rule uses this option, it does not need a `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 this 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. | +| `neverlink` | Boolean; default is `False` | +| `plugins` | List of [labels](/concepts/labels); default is `[]` Java compiler plugins to run at compile-time. Every `java_plugin` specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use `exported_plugins`. Resources generated by the plugin will be included in the resulting jar of this rule. | +| `resource_strip_prefix` | String; default is `""` The path prefix to strip from Java resources. If specified, this path prefix is stripped from every file in the `resources` attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at `stuff/java/foo/bar/a.txt` will be located at `foo/bar/a.txt`. | +| `runtime_deps` | List of [labels](/concepts/labels); default is `[]` Libraries to make available to the final binary or test at runtime only. Like ordinary `deps`, these will appear on the runtime classpath, but unlike them, not on the compile-time classpath. Dependencies needed only at runtime should be listed here. Dependency-analysis tools should ignore targets that appear in both `runtime_deps` and `deps`. | +| `stamp` | Integer; default is `-1` Whether to encode build information into the binary. Possible values: * `stamp = 1`: Always stamp the build information into the binary, even in [`--nostamp`](/docs/user-manual#flag--stamp) builds. **This setting should be avoided**, since it potentially kills remote caching for the binary and any downstream actions that depend on it. * `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`](/docs/user-manual#flag--stamp) flag. Stamped binaries are *not* rebuilt unless their dependencies change. | +| `use_launcher` | Boolean; default is `True` Whether the binary should use a custom launcher. If this attribute is set to false, the [launcher](/reference/be/java#java_binary.launcher) attribute and the related [`--java_launcher`](/docs/user-manual#flag--java_launcher) flag will be ignored for this target. | +| `use_testrunner` | Boolean; default is `False` Use the test runner (by default `com.google.testing.junit.runner.BazelTestRunner`) class as the main entry point for a Java program, and provide the test class to the test runner as a value of `bazel.test_suite` system property. You can use this to override the default behavior, which is to use test runner for `java_test` rules, and not use it for `java_binary` rules. 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. The name of a test runner class can be overridden with `main_class` attribute. | + +## java_import + +[View rule sourceopen_in_new](@rules_java//java/bazel/rules/bazel_java_import.bzl) + +``` +java_import(name, deps, data, add_exports, add_opens, compatible_with, constraints, deprecation, distribs, exec_compatible_with, exec_properties, exports, features, jars, licenses, neverlink, proguard_specs, restricted_to, runtime_deps, srcjar, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +This rule allows the use of precompiled `.jar` files as +libraries for `java_library` and +`java_binary` rules. + +#### Examples + +``` + java_import( + name = "maven_model", + jars = [ + "maven_model/maven-aether-provider-3.2.3.jar", + "maven_model/maven-model-3.2.3.jar", + "maven_model/maven-model-builder-3.2.3.jar", + ], + ) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries to be linked in to the target. See [java_library.deps](/reference/be/java#java_library.deps). | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this rule at runtime. | +| `add_exports` | List of strings; default is `[]` Allow this library to access the given `module` or `package`. This corresponds to the javac and JVM --add-exports= flags. | +| `add_opens` | List of strings; default is `[]` Allow this library to reflectively access the given `module` or `package`. This corresponds to the javac and JVM --add-opens= flags. | +| `constraints` | List of strings; default is `[]` Extra constraints imposed on this rule as a Java library. | +| `exports` | List of [labels](/concepts/labels); default is `[]` Targets to make available to users of this rule. See [java_library.exports](/reference/be/java#java_library.exports). | +| `jars` | List of [labels](/concepts/labels); required The list of JAR files provided to Java targets that depend on this target. | +| `neverlink` | Boolean; default is `False` Only use this library for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of libraries like this are IDE APIs for IDE plug-ins or `tools.jar` for anything running on a standard JDK. | +| `proguard_specs` | List of [labels](/concepts/labels); default is `[]` Files to be used as Proguard specification. These will describe the set of specifications to be used by Proguard. If specified, they will be added to any `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. | +| `runtime_deps` | List of [labels](/concepts/labels); default is `[]` Libraries to make available to the final binary or test at runtime only. See [java_library.runtime_deps](/reference/be/java#java_library.runtime_deps). | +| `srcjar` | [Label](/concepts/labels); default is `None` A JAR file that contains source code for the compiled JAR files. | + +## java_library + +[View rule sourceopen_in_new](@rules_java//java/bazel/rules/bazel_java_library.bzl) + +``` +java_library(name, deps, srcs, data, resources, add_exports, add_opens, bootclasspath, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, exported_plugins, exports, features, javabuilder_jvm_flags, javacopts, licenses, neverlink, plugins, proguard_specs, resource_strip_prefix, restricted_to, runtime_deps, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +This rule compiles and links sources into a `.jar` file. + +#### Implicit outputs + +* `libname.jar`: A Java archive containing the class files. +* `libname-src.jar`: An archive containing the sources ("source + jar"). + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of libraries to link into this library. See general comments about `deps` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). The jars built by `java_library` rules listed in `deps` will be on the compile-time classpath of this rule. Furthermore 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` | List of [labels](/concepts/labels); default is `[]` The list of source files that are processed to create the target. This attribute is almost always required; see exceptions below. Source files of type `.java` are compiled. In case of generated `.java` files it is generally advisable to put the generating rule's name here instead of the name of the file itself. This not only improves readability but makes the rule 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. You should not list the generating rule in `deps` because it is a no-op. Source files of type `.srcjar` are unpacked and compiled. (This is useful if you need to generate a set of `.java` files with a genrule.) Rules: if the rule (typically `genrule` or `filegroup`) generates any of the files listed above, they will be used the same way as described for source files. Source files of type `.properties` are treated as resources. All other files are ignored, as long as there is at least one file of a file type described above. Otherwise an error is raised. This argument is almost always required, except if you specify the `runtime_deps` argument. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this library at runtime. See general comments about `data` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). When building a `java_library`, Bazel doesn't put these files anywhere; if the `data` files are generated files then Bazel generates them. When building a test that depends on this `java_library` Bazel copies or links the `data` files into the runfiles area. | +| `resources` | List of [labels](/concepts/labels); default is `[]` A list of data files to include in a Java jar. Resources may be source files or generated files. If resources are specified, they will be bundled in the jar along with the usual `.class` files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven's [standard directory layout](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html), (a "src" directory followed by a "resources" directory grandchild). If that is not found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for example, if a resource is at `<workspace root>/x/java/y/java/z`, the path of the resource will be `y/java/z`. This heuristic cannot be overridden, however, the `resource_strip_prefix` attribute can be used to specify a specific alternative directory for resource files. | +| `add_exports` | List of strings; default is `[]` Allow this library to access the given `module` or `package`. This corresponds to the javac and JVM --add-exports= flags. | +| `add_opens` | List of strings; default is `[]` Allow this library to reflectively access the given `module` or `package`. This corresponds to the javac and JVM --add-opens= flags. | +| `bootclasspath` | [Label](/concepts/labels); default is `None` Restricted API, do not use! | +| `exported_plugins` | List of [labels](/concepts/labels); default is `[]` The list of `java_plugin`s (e.g. annotation processors) to export to libraries that directly depend on this library. 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` | List of [labels](/concepts/labels); default is `[]` Exported libraries. Listing rules here will make them available to parent rules, as if the parents explicitly depended on these rules. This is not true for regular (non-exported) `deps`. Summary: a rule *X* can access the code in *Y* if there exists a dependency path between them that begins with a `deps` edge followed by zero or more `exports` edges. Let's see some examples to illustrate this. Assume *A* depends on *B* and *B* depends on *C*. In this case C is a *transitive* dependency of A, so changing C's sources and rebuilding A will correctly rebuild everything. However A will not be able to use classes in C. To allow that, either A has to declare C in its `deps`, or B can make it easier for A (and anything that may depend on A) by declaring C in its (B's) `exports` attribute. The closure of exported libraries is available to all direct parent rules. Take a slightly different example: A depends on B, B depends on C and D, and also exports C but not D. Now A has access to C but not to D. Now, if C and D exported some libraries, C' and D' respectively, A could only access C' but not D'. Important: an exported rule is not a regular dependency. Sticking to the previous example, if B exports C and wants to also use C, it has to also list it in its own `deps`. | +| `javabuilder_jvm_flags` | List of strings; default is `[]` Restricted API, do not use! | +| `javacopts` | List of strings; default is `[]` Extra compiler options for this library. Subject to ["Make variable"](make-variables) substitution and [Bourne shell tokenization](common-definitions#sh-tokenization). These compiler options are passed to javac after the global compiler options. | +| `neverlink` | Boolean; default is `False` Whether this library should only be used for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of such libraries are the IDE APIs for IDE plug-ins or `tools.jar` for anything running on a standard JDK. Note that `neverlink = True` 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 of primitive types). 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 to inline (and that must hold for all future versions of the JLS). | +| `plugins` | List of [labels](/concepts/labels); default is `[]` Java compiler plugins to run at compile-time. Every `java_plugin` specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use `exported_plugins`. Resources generated by the plugin will be included in the resulting jar of this rule. | +| `proguard_specs` | List of [labels](/concepts/labels); default is `[]` Files to be used as Proguard specification. These will describe the set of specifications to be used by Proguard. If specified, they will be added to any `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. | +| `resource_strip_prefix` | String; default is `""` The path prefix to strip from Java resources. If specified, this path prefix is stripped from every file in the `resources` attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at `stuff/java/foo/bar/a.txt` will be located at `foo/bar/a.txt`. | +| `runtime_deps` | List of [labels](/concepts/labels); default is `[]` Libraries to make available to the final binary or test at runtime only. Like ordinary `deps`, these will appear on the runtime classpath, but unlike them, not on the compile-time classpath. Dependencies needed only at runtime should be listed here. Dependency-analysis tools should ignore targets that appear in both `runtime_deps` and `deps`. | + +## java_test + +[View rule sourceopen_in_new](@rules_java//java/bazel/rules/bazel_java_test.bzl) + +``` +java_test(name, deps, srcs, data, resources, add_exports, add_opens, args, bootclasspath, classpath_resources, compatible_with, create_executable, deploy_manifest_lines, deprecation, distribs, env, env_inherit, exec_compatible_with, exec_properties, features, flaky, javacopts, jvm_flags, launcher, licenses, local, main_class, neverlink, plugins, resource_strip_prefix, restricted_to, runtime_deps, shard_count, size, stamp, tags, target_compatible_with, test_class, testonly, timeout, toolchains, use_launcher, use_testrunner, visibility) +``` + +A `java_test()` rule compiles a Java test. A test is a binary wrapper around your +test code. The test runner's main method is invoked instead of the main class being compiled. + +#### Implicit output targets + +* `name.jar`: A Java archive. +* `name_deploy.jar`: A Java archive suitable + for deployment. (Only built if explicitly requested.) See the description of the + `name_deploy.jar` output from + [java_binary](#java_binary) for more details. + +See the section on `java_binary()` arguments. This rule also +supports all [attributes common +to all test rules (\*\_test)](https://bazel.build/reference/be/common-definitions#common-attributes-tests). + +#### Examples + +``` +java_library( + name = "tests", + srcs = glob(["*.java"]), + deps = [ + "//java/com/foo/base:testResources", + "//java/com/foo/testing/util", + ], +) + +java_test( + name = "AllTests", + size = "small", + runtime_deps = [ + ":tests", + "//util/mysql", + ], +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries to be linked in to the target. See general comments about `deps` at [Typical attributes defined by most build rules](common-definitions#typical-attributes). | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of source files that are processed to create the target. This attribute is almost always required; see exceptions below. Source files of type `.java` are compiled. In case of generated `.java` files it is generally advisable to put the generating rule's name here instead of the name of the file itself. This not only improves readability but makes the rule 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. You should not list the generating rule in `deps` because it is a no-op. Source files of type `.srcjar` are unpacked and compiled. (This is useful if you need to generate a set of `.java` files with a genrule.) Rules: if the rule (typically `genrule` or `filegroup`) generates any of the files listed above, they will be used the same way as described for source files. This argument is almost always required, except if a [`main_class`](#java_binary.main_class) attribute specifies a class on the runtime classpath or you specify the `runtime_deps` argument. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this library at runtime. See general comments about `data` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). | +| `resources` | List of [labels](/concepts/labels); default is `[]` A list of data files to include in a Java jar. Resources may be source files or generated files. If resources are specified, they will be bundled in the jar along with the usual `.class` files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven's [standard directory layout](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html), (a "src" directory followed by a "resources" directory grandchild). If that is not found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for example, if a resource is at `<workspace root>/x/java/y/java/z`, the path of the resource will be `y/java/z`. This heuristic cannot be overridden, however, the `resource_strip_prefix` attribute can be used to specify a specific alternative directory for resource files. | +| `add_exports` | List of strings; default is `[]` Allow this library to access the given `module` or `package`. This corresponds to the javac and JVM --add-exports= flags. | +| `add_opens` | List of strings; default is `[]` Allow this library to reflectively access the given `module` or `package`. This corresponds to the javac and JVM --add-opens= flags. | +| `bootclasspath` | [Label](/concepts/labels); default is `None` Restricted API, do not use! | +| `classpath_resources` | List of [labels](/concepts/labels); default is `[]` *DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY)* A list of resources that must be located at the root of the java tree. This attribute's only purpose is to support third-party libraries that require 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` | Boolean; default is `True` Deprecated, use `java_single_jar` instead. | +| `deploy_manifest_lines` | List of strings; default is `[]` A list of lines to add to the `META-INF/manifest.mf` file generated for the `*_deploy.jar` target. The contents of this attribute are *not* subject to ["Make variable"](make-variables) substitution. | +| `javacopts` | List of strings; default is `[]` Extra compiler options for this binary. Subject to ["Make variable"](make-variables) substitution and [Bourne shell tokenization](common-definitions#sh-tokenization). These compiler options are passed to javac after the global compiler options. | +| `jvm_flags` | List of strings; default is `[]` A list of flags to embed in the wrapper script generated for running this binary. Subject to [$(location)](/reference/be/make-variables#location) and ["Make variable"](make-variables) substitution, and [Bourne shell tokenization](common-definitions#sh-tokenization). The wrapper script for a Java binary includes a CLASSPATH definition (to find all the dependent jars) and invokes the right Java interpreter. The command line generated by the wrapper script includes the name of the main class followed by a `"$@"` 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. Note that this attribute has *no effect* on `*_deploy.jar` outputs. | +| `launcher` | [Label](/concepts/labels); default is `None` Specify a binary that will be used to run your Java program instead of the normal `bin/java` program included with the JDK. The target must be a `cc_binary`. Any `cc_binary` that implements the [Java Invocation API](http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/invocation.html) can be specified as a value for this attribute. By default, Bazel will use the normal JDK launcher (bin/java or java.exe). The related [`--java_launcher`](/docs/user-manual#flag--java_launcher) Bazel flag affects only those `java_binary` and `java_test` targets that have *not* specified a `launcher` attribute. Note that your native (C++, SWIG, JNI) dependencies will be built differently depending on whether you are using the JDK launcher or another launcher: * If you are using the normal JDK launcher (the default), native dependencies are built as a shared library named `{name}_nativedeps.so`, where `{name}` is the `name` attribute of this java_binary rule. Unused code is *not* removed by the linker in this configuration. * If you are using any other launcher, native (C++) dependencies are statically linked into a binary named `{name}_nativedeps`, where `{name}` is the `name` attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless that `cc_library` target specifies `alwayslink = True`. When using any launcher other than the default JDK launcher, the format of the `*_deploy.jar` output changes. See the main [java_binary](#java_binary) docs for details. | +| `main_class` | String; default is `""` Name of class with `main()` method to use as entry point. If a rule uses this option, it does not need a `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 this 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. | +| `neverlink` | Boolean; default is `False` | +| `plugins` | List of [labels](/concepts/labels); default is `[]` Java compiler plugins to run at compile-time. Every `java_plugin` specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use `exported_plugins`. Resources generated by the plugin will be included in the resulting jar of this rule. | +| `resource_strip_prefix` | String; default is `""` The path prefix to strip from Java resources. If specified, this path prefix is stripped from every file in the `resources` attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at `stuff/java/foo/bar/a.txt` will be located at `foo/bar/a.txt`. | +| `runtime_deps` | List of [labels](/concepts/labels); default is `[]` Libraries to make available to the final binary or test at runtime only. Like ordinary `deps`, these will appear on the runtime classpath, but unlike them, not on the compile-time classpath. Dependencies needed only at runtime should be listed here. Dependency-analysis tools should ignore targets that appear in both `runtime_deps` and `deps`. | +| `stamp` | Integer; default is `0` Whether to encode build information into the binary. Possible values: * `stamp = 1`: Always stamp the build information into the binary, even in [`--nostamp`](https://bazel.build/docs/user-manual#stamp) builds. **This setting should be avoided**, since it potentially kills remote caching for the binary and any downstream actions that depend on it. * `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`](https://bazel.build/docs/user-manual#stamp) flag. Stamped binaries are *not* rebuilt unless their dependencies change. | +| `test_class` | String; default is `""` The Java class to be loaded by the test runner. By default, if this argument is not defined then the legacy mode is used and the test arguments are used instead. Set the `--nolegacy_bazel_java_test` flag to not fallback on the first argument. This attribute specifies the name of a Java class to be run by this test. It is rare to need to set this. If this argument is omitted, it will be inferred using the target's `name` and its source-root-relative path. If the test is located outside a known source root, Bazel will report an error if `test_class` is unset. For JUnit3, the test 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`). 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. | +| `use_launcher` | Boolean; default is `True` Whether the binary should use a custom launcher. If this attribute is set to false, the [launcher](/reference/be/java#java_binary.launcher) attribute and the related [`--java_launcher`](/docs/user-manual#flag--java_launcher) flag will be ignored for this target. | +| `use_testrunner` | Boolean; default is `True` Use the test runner (by default `com.google.testing.junit.runner.BazelTestRunner`) class as the main entry point for a Java program, and provide the test class to the test runner as a value of `bazel.test_suite` system property. You can use this to override the default behavior, which is to use test runner for `java_test` rules, and not use it for `java_binary` rules. 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. The name of a test runner class can be overridden with `main_class` attribute. | + +## java_package_configuration + +[View rule sourceopen_in_new](@rules_java//java/common/rules/java_package_configuration.bzl) + +``` +java_package_configuration(name, data, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, javacopts, output_licenses, packages, restricted_to, system, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Configuration to apply to a set of packages. +Configurations can be added to +`java_toolchain.javacopts`s. + +#### Example: + +``` +java_package_configuration( + name = "my_configuration", + packages = [":my_packages"], + javacopts = ["-Werror"], +) + +package_group( + name = "my_packages", + packages = [ + "//com/my/project/...", + "-//com/my/project/testing/...", + ], +) + +java_toolchain( + ..., + package_configuration = [ + ":my_configuration", + ] +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this configuration at runtime. | +| `javacopts` | List of strings; default is `[]` Java compiler flags. | +| `output_licenses` | List of strings; default is `[]` | +| `packages` | List of [labels](/concepts/labels); default is `[]` The set of `package_group`s the configuration should be applied to. | +| `system` | [Label](/concepts/labels); default is `None` Corresponds to javac's --system flag. | + +## java_plugin + +[View rule sourceopen_in_new](@rules_java//java/bazel/rules/bazel_java_plugin.bzl) + +``` +java_plugin(name, deps, srcs, data, resources, add_exports, add_opens, bootclasspath, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, generates_api, javabuilder_jvm_flags, javacopts, licenses, neverlink, output_licenses, plugins, processor_class, proguard_specs, resource_strip_prefix, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +`java_plugin` defines plugins for the Java compiler run by Bazel. 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 automatically export plugins to libraries that +directly depend on it using +`exported_plugins`. + +#### Implicit output targets + +* `libname.jar`: A Java archive. + +Arguments are a subset of (and with identical semantics to) those of +[java_library()](/reference/be/java#java_library), +except for the addition of the `processor_class` and +`generates_api` arguments. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of libraries to link into this library. See general comments about `deps` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). The jars built by `java_library` rules listed in `deps` will be on the compile-time classpath of this rule. Furthermore 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` | List of [labels](/concepts/labels); default is `[]` The list of source files that are processed to create the target. This attribute is almost always required; see exceptions below. Source files of type `.java` are compiled. In case of generated `.java` files it is generally advisable to put the generating rule's name here instead of the name of the file itself. This not only improves readability but makes the rule 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. You should not list the generating rule in `deps` because it is a no-op. Source files of type `.srcjar` are unpacked and compiled. (This is useful if you need to generate a set of `.java` files with a genrule.) Rules: if the rule (typically `genrule` or `filegroup`) generates any of the files listed above, they will be used the same way as described for source files. Source files of type `.properties` are treated as resources. All other files are ignored, as long as there is at least one file of a file type described above. Otherwise an error is raised. This argument is almost always required, except if you specify the `runtime_deps` argument. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this library at runtime. See general comments about `data` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). When building a `java_library`, Bazel doesn't put these files anywhere; if the `data` files are generated files then Bazel generates them. When building a test that depends on this `java_library` Bazel copies or links the `data` files into the runfiles area. | +| `resources` | List of [labels](/concepts/labels); default is `[]` A list of data files to include in a Java jar. Resources may be source files or generated files. If resources are specified, they will be bundled in the jar along with the usual `.class` files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven's [standard directory layout](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html), (a "src" directory followed by a "resources" directory grandchild). If that is not found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for example, if a resource is at `<workspace root>/x/java/y/java/z`, the path of the resource will be `y/java/z`. This heuristic cannot be overridden, however, the `resource_strip_prefix` attribute can be used to specify a specific alternative directory for resource files. | +| `add_exports` | List of strings; default is `[]` Allow this library to access the given `module` or `package`. This corresponds to the javac and JVM --add-exports= flags. | +| `add_opens` | List of strings; default is `[]` Allow this library to reflectively access the given `module` or `package`. This corresponds to the javac and JVM --add-opens= flags. | +| `bootclasspath` | [Label](/concepts/labels); default is `None` Restricted API, do not use! | +| `generates_api` | Boolean; default is `False` This attribute marks annotation processors that generate API code. If a rule uses an API-generating annotation processor, other rules depending on it can refer to the generated code only if their compilation actions are scheduled after the generating rule. This attribute instructs Bazel to introduce scheduling constraints when --java_header_compilation is enabled. *WARNING: This attribute affects build performance, use it only if necessary.* | +| `javabuilder_jvm_flags` | List of strings; default is `[]` Restricted API, do not use! | +| `javacopts` | List of strings; default is `[]` Extra compiler options for this library. Subject to ["Make variable"](make-variables) substitution and [Bourne shell tokenization](common-definitions#sh-tokenization). These compiler options are passed to javac after the global compiler options. | +| `neverlink` | Boolean; default is `False` Whether this library should only be used for compilation and not at runtime. Useful if the library will be provided by the runtime environment during execution. Examples of such libraries are the IDE APIs for IDE plug-ins or `tools.jar` for anything running on a standard JDK. Note that `neverlink = True` 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 of primitive types). 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 to inline (and that must hold for all future versions of the JLS). | +| `output_licenses` | List of strings; default is `[]` | +| `plugins` | List of [labels](/concepts/labels); default is `[]` Java compiler plugins to run at compile-time. Every `java_plugin` specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use `exported_plugins`. Resources generated by the plugin will be included in the resulting jar of this rule. | +| `processor_class` | String; default is `""` The processor class is the fully qualified type of the class that the Java compiler should use as entry point to the annotation processor. If not specified, this rule 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. (This is primarily intended for use by [Error Prone plugins](https://errorprone.info/docs/plugins), which are loaded from the annotation processor path using [java.util.ServiceLoader](https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html).) | +| `proguard_specs` | List of [labels](/concepts/labels); default is `[]` Files to be used as Proguard specification. These will describe the set of specifications to be used by Proguard. If specified, they will be added to any `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. | +| `resource_strip_prefix` | String; default is `""` The path prefix to strip from Java resources. If specified, this path prefix is stripped from every file in the `resources` attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at `stuff/java/foo/bar/a.txt` will be located at `foo/bar/a.txt`. | + +## java_runtime + +[View rule sourceopen_in_new](@rules_java//java/common/rules/java_runtime.bzl) + +``` +java_runtime(name, srcs, compatible_with, default_cds, deprecation, distribs, exec_compatible_with, exec_properties, features, hermetic_srcs, hermetic_static_libs, java, java_home, lib_ct_sym, lib_modules, output_licenses, restricted_to, tags, target_compatible_with, testonly, toolchains, version, visibility) +``` + +Specifies the configuration for a Java runtime. + +#### Example: + +``` +java_runtime( + name = "jdk-9-ea+153", + srcs = glob(["jdk9-ea+153/**"]), + java_home = "jdk9-ea+153", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` All files in the runtime. | +| `default_cds` | [Label](/concepts/labels); default is `None` Default CDS archive for hermetic `java_runtime`. When hermetic is enabled for a `java_binary` target the `java_runtime` default CDS is packaged in the hermetic deploy JAR. | +| `hermetic_srcs` | List of [labels](/concepts/labels); default is `[]` Files in the runtime needed for hermetic deployments. | +| `hermetic_static_libs` | List of [labels](/concepts/labels); default is `[]` The libraries that are statically linked with the launcher for hermetic deployments | +| `java` | [Label](/concepts/labels); default is `None` The path to the java executable. | +| `java_home` | String; default is `""` The path to the root of the runtime. Subject to ["Make" variable](/reference/be/make-variables) substitution. If this path is absolute, the rule denotes a non-hermetic Java runtime with a well-known path. In that case, the `srcs` and `java` attributes must be empty. | +| `lib_ct_sym` | [Label](/concepts/labels); default is `None` The lib/ct.sym file needed for compilation with `--release`. If not specified and there is exactly one file in `srcs` whose path ends with `/lib/ct.sym`, that file is used. | +| `lib_modules` | [Label](/concepts/labels); default is `None` The lib/modules file needed for hermetic deployments. | +| `output_licenses` | List of strings; default is `[]` | +| `version` | Integer; default is `0` The feature version of the Java runtime. I.e., the integer returned by `Runtime.version().feature()`. | + +## java_toolchain + +[View rule sourceopen_in_new](@rules_java//java/common/rules/java_toolchain.bzl) + +``` +java_toolchain(name, android_lint_data, android_lint_jvm_opts, android_lint_opts, android_lint_package_configuration, android_lint_runner, bootclasspath, compatible_javacopts, compatible_with, deprecation, deps_checker, distribs, exec_compatible_with, exec_properties, features, forcibly_disable_header_compilation, genclass, header_compiler, header_compiler_builtin_processors, header_compiler_direct, ijar, jacocorunner, java_runtime, javabuilder, javabuilder_data, javabuilder_jvm_opts, javac_supports_multiplex_workers, javac_supports_worker_cancellation, javac_supports_worker_multiplex_sandboxing, javac_supports_workers, javacopts, jspecify_implicit_deps, jspecify_javacopts, jspecify_packages, jspecify_processor, jspecify_processor_class, jspecify_stubs, jvm_opts, licenses, misc, oneversion, oneversion_allowlist, oneversion_allowlist_for_tests, oneversion_whitelist, package_configuration, proguard_allowlister, reduced_classpath_incompatible_processors, restricted_to, singlejar, source_version, tags, target_compatible_with, target_version, testonly, timezone_data, toolchains, tools, turbine_data, turbine_jvm_opts, visibility, xlint) +``` + +Specifies the configuration for the Java compiler. Which toolchain to be used can be changed through +the --java_toolchain argument. Normally you should not write those kind of rules unless you want to +tune your Java compiler. + +#### Examples + +A simple example would be: + +``` +java_toolchain( + name = "toolchain", + source_version = "7", + target_version = "7", + bootclasspath = ["//tools/jdk:bootclasspath"], + xlint = [ "classfile", "divzero", "empty", "options", "path" ], + javacopts = [ "-g" ], + javabuilder = ":JavaBuilder_deploy.jar", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `android_lint_data` | List of [labels](/concepts/labels); default is `[]` Labels of tools available for label-expansion in android_lint_jvm_opts. | +| `android_lint_jvm_opts` | List of strings; default is `[]` The list of arguments for the JVM when invoking Android Lint. | +| `android_lint_opts` | List of strings; default is `[]` The list of Android Lint arguments. | +| `android_lint_package_configuration` | List of [labels](/concepts/labels); default is `[]` Android Lint Configuration that should be applied to the specified package groups. | +| `android_lint_runner` | [Label](/concepts/labels); default is `None` Label of the Android Lint runner, if any. | +| `bootclasspath` | List of [labels](/concepts/labels); default is `[]` The Java target bootclasspath entries. Corresponds to javac's -bootclasspath flag. | +| `compatible_javacopts` | null; default is `{}` Internal API, do not use! | +| `deps_checker` | [Label](/concepts/labels); default is `None` Label of the ImportDepsChecker deploy jar. | +| `forcibly_disable_header_compilation` | Boolean; default is `False` Overrides --java_header_compilation to disable header compilation on platforms that do not support it, e.g. JDK 7 Bazel. | +| `genclass` | [Label](/concepts/labels); default is `None` Label of the GenClass deploy jar. | +| `header_compiler` | [Label](/concepts/labels); default is `None` Label of the header compiler. Required if --java_header_compilation is enabled. | +| `header_compiler_builtin_processors` | List of strings; default is `[]` Internal API, do not use! | +| `header_compiler_direct` | [Label](/concepts/labels); default is `None` Optional label of the header compiler to use for direct classpath actions that do not include any API-generating annotation processors. This tool does not support annotation processing. | +| `ijar` | [Label](/concepts/labels); default is `None` Label of the ijar executable. | +| `jacocorunner` | [Label](/concepts/labels); default is `None` Label of the JacocoCoverageRunner deploy jar. | +| `java_runtime` | [Label](/concepts/labels); default is `None` The java_runtime to use with this toolchain. It defaults to java_runtime in execution configuration. | +| `javabuilder` | [Label](/concepts/labels); default is `None` Label of the JavaBuilder deploy jar. | +| `javabuilder_data` | List of [labels](/concepts/labels); default is `[]` Labels of data available for label-expansion in javabuilder_jvm_opts. | +| `javabuilder_jvm_opts` | List of strings; default is `[]` The list of arguments for the JVM when invoking JavaBuilder. | +| `javac_supports_multiplex_workers` | Boolean; default is `True` True if JavaBuilder supports running as a multiplex persistent worker, false if it doesn't. | +| `javac_supports_worker_cancellation` | Boolean; default is `True` True if JavaBuilder supports cancellation of persistent workers, false if it doesn't. | +| `javac_supports_worker_multiplex_sandboxing` | Boolean; default is `False` True if JavaBuilder supports running as a multiplex persistent worker with sandboxing, false if it doesn't. | +| `javac_supports_workers` | Boolean; default is `True` True if JavaBuilder supports running as a persistent worker, false if it doesn't. | +| `javacopts` | List of strings; default is `[]` The list of extra arguments for the Java compiler. Please refer to the Java compiler documentation for the extensive list of possible Java compiler flags. | +| `jspecify_implicit_deps` | [Label](/concepts/labels); default is `None` Experimental, do not use! | +| `jspecify_javacopts` | List of strings; default is `[]` Experimental, do not use! | +| `jspecify_packages` | List of [labels](/concepts/labels); default is `[]` Experimental, do not use! | +| `jspecify_processor` | [Label](/concepts/labels); default is `None` Experimental, do not use! | +| `jspecify_processor_class` | String; default is `""` Experimental, do not use! | +| `jspecify_stubs` | List of [labels](/concepts/labels); default is `[]` Experimental, do not use! | +| `jvm_opts` | List of strings; default is `[]` The list of arguments for the JVM when invoking the Java compiler. Please refer to the Java virtual machine documentation for the extensive list of possible flags for this option. | +| `misc` | List of strings; default is `[]` Deprecated: use javacopts instead | +| `oneversion` | [Label](/concepts/labels); default is `None` Label of the one-version enforcement binary. | +| `oneversion_allowlist` | [Label](/concepts/labels); default is `None` Label of the one-version allowlist. | +| `oneversion_allowlist_for_tests` | [Label](/concepts/labels); default is `None` Label of the one-version allowlist for tests. | +| `oneversion_whitelist` | [Label](/concepts/labels); default is `None` Deprecated: use oneversion_allowlist instead | +| `package_configuration` | List of [labels](/concepts/labels); default is `[]` Configuration that should be applied to the specified package groups. | +| `proguard_allowlister` | [Label](/concepts/labels); default is `"@bazel_tools//tools/jdk:proguard_whitelister"` Label of the Proguard allowlister. | +| `reduced_classpath_incompatible_processors` | List of strings; default is `[]` Internal API, do not use! | +| `singlejar` | [Label](/concepts/labels); default is `None` Label of the SingleJar deploy jar. | +| `source_version` | String; default is `""` The Java source version (e.g., '6' or '7'). It specifies which set of code structures are allowed in the Java source code. | +| `target_version` | String; default is `""` The Java target version (e.g., '6' or '7'). It specifies for which Java runtime the class should be build. | +| `timezone_data` | [Label](/concepts/labels); default is `None` Label of a resource jar containing timezone data. If set, the timezone data is added as an implicitly runtime dependency of all java_binary rules. | +| `tools` | List of [labels](/concepts/labels); default is `[]` Labels of tools available for label-expansion in jvm_opts. | +| `turbine_data` | List of [labels](/concepts/labels); default is `[]` Labels of data available for label-expansion in turbine_jvm_opts. | +| `turbine_jvm_opts` | List of strings; default is `[]` The list of arguments for the JVM when invoking turbine. | +| `xlint` | List of strings; default is `[]` The list of warning to add or removes from default list. Precedes it with a dash to removes it. Please see the Javac documentation on the -Xlint options for more information. | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/make-variables.mdx b/versions/8.6.0/reference/be/make-variables.mdx new file mode 100644 index 00000000..b527affb --- /dev/null +++ b/versions/8.6.0/reference/be/make-variables.mdx @@ -0,0 +1,311 @@ +--- +title: 'Make Variables' +--- + +* [Use](#use) +* [Predefined variables](#predefined_variables) +* [Predefined genrule variables](#predefined_genrule_variables) +* [Predefined source/output path variables](#predefined_label_variables) +* [Custom variables](#custom_variables) + +"Make" variables are a special class of expandable string variables available +to attributes marked as *"Subject to 'Make variable' substitution"*. + +These can be used, for example, to inject specific toolchain paths into +user-constructed build actions. + +Bazel provides both *predefined* variables, which are available to all +targets, and *custom* variables, which are defined in dependency targets +and only available to targets that depend on them. + +The reason for the term "Make" is historical: the syntax and semantics of +these variables were originally intended to match [GNU +Make](https://www.gnu.org/software/make/manual/html_node/Using-Variables.html). + +## Use + +Attributes marked as *"Subject to 'Make variable' substitution"* can +reference the "Make" variable `FOO` as follows: + +`my_attr = "prefix $(FOO) suffix"` + +In other words, any substring matching `$(FOO)` gets expanded +to `FOO`'s value. If that value is `"bar"`, the final +string becomes: + +`my_attr = "prefix bar suffix"` + +If `FOO` doesn't correspond to a variable known to the consuming +target, Bazel fails with an error. + +"Make" variables whose names are non-letter symbols, such as +`@`, can also be referenced using only a dollar sign, without +the parentheses. For example: + +`my_attr = "prefix $@ suffix"` + +To write `$` as a string literal (i.e. to prevent variable +expansion), write `$$`. + +## Predefined variables + +Predefined "Make" variables can be referenced by any attribute marked as +*"Subject to 'Make variable' substitution"* on any target. + +To see the list of these variables and their values for a given set of build +options, run + +`bazel info --show_make_env [build options]` + +and look at the top output lines with capital letters. + +[See an example of predefined variables](https://github.com/bazelbuild/examples/tree/main/make-variables#predefined-variables). + +**Toolchain option variables** + +* `COMPILATION_MODE`: + `fastbuild`, `dbg`, or `opt`. ([more + details](https://bazel.build/docs/user-manual#flag--compilation_mode)) + +**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 to get its path is `$(execpath toolname)`, + where *toolname* must be listed in the `genrule`'s + `tools` attribute. +* `GENDIR`: + The base of the generated code tree for the target architecture. + +**Machine architecture variables** + +* `TARGET_CPU`: + The target architecture's CPU, e.g. `k8`. + +## Predefined genrule variables + +The following are specially available to `genrule`'s +`cmd` attribute and are +generally important for making that attribute work. + +[See an example of predefined genrule variables](https://github.com/bazelbuild/examples/tree/main/make-variables#predefined-genrule-variables). + +* `OUTS`: The `genrule`'s `outs` list. If you have + only one output file, you can also use `$@`. +* `SRCS`: The `genrule`'s `srcs` list (or more + precisely: the path names 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. Else triggers + a build error. +* `@`: `OUTS`, if it is a single file. Else triggers a + build error. +* `RULEDIR`: The output directory of the target, that is, the + directory corresponding to the name of the package containing the target + under the `genfiles` or `bin` tree. For + `//my/pkg:my_genrule` this always ends in `my/pkg`, + even if `//my/pkg:my_genrule`'s outputs are in subdirectories. +* `@D`: The output directory. If + [outs](/reference/be/general#genrule.outs) has one entry, + this expands to the directory containing that file. If it has multiple + entries, this expands to the package's root directory in the + `genfiles` tree, *even if all output files are in the same + subdirectory*! + + **Note:** Use `RULEDIR` over `@D` because + `RULEDIR` has simpler semantics and behaves the same way + regardless of the number of output files. + + If the genrule needs to generate temporary intermediate files (perhaps as + a result of using some other tool like a compiler), it should attempt to + write them to `@D` (although `/tmp` will also + be writable) and remove them before finishing. + + Especially avoid writing to directories containing inputs. They may be on + read-only filesystems. Even if not, doing so would trash the source tree. + +## Predefined source/output path variables + +The predefined variables `execpath`, `execpaths`, +`rootpath`, `rootpaths`, `location`, and +`locations` take label parameters (e.g. `$(execpath +//foo:bar)`) and substitute the file paths denoted by that label. + +For source files, this is the path relative to your workspace root. +For files that are outputs of rules, this is the file's *output path* +(see the explanation of *output files* below). + +[See an example of predefined path variables](https://github.com/bazelbuild/examples/tree/main/make-variables#predefined-path-variables). + +* `execpath`: Denotes the path beneath the + [execroot](/docs/output_directories) + where Bazel runs build actions. + + In the above example, Bazel runs all build actions in the directory linked + by the `bazel-myproject` symlink in your workspace root. The + source file `empty.source` is linked at the path + `bazel-myproject/testapp/empty.source`. So its exec path (which + is the subpath below the root) is `testapp/empty.source`. This + is the path build actions can use to find the file. + + Output files are staged similarly, but are also prefixed with the subpath + `bazel-out/cpu-compilation_mode/bin` (or for the outputs of + tools: `bazel-out/cpu-opt-exec-hash/bin`). In the above example, + `//testapp:app` is a tool because it appears in + `show_app_output`'s `tools` attribute. + So its output file `app` is written to + `bazel-myproject/bazel-out/cpu-opt-exec-hash/bin/testapp/app`. + The exec path is thus `bazel-out/cpu-opt-exec-hash/bin/testapp/app`. This extra prefix + makes it possible to build the same target for, say, two different CPUs in + the same build without the results clobbering each other. + + The label passed to this variable must represent exactly one file. For + labels representing source files, this is automatically true. For labels + representing rules, the rule must generate exactly one output. If this is + false or the label is malformed, the build fails with an error. +* `rootpath`: Denotes the path that a built binary can use to + find a dependency at runtime relative to the subdirectory of its runfiles + directory corresponding to the main repository. + **Note:** This only works if [`--enable_runfiles`](/reference/command-line-reference#flag--enable_runfiles) is enabled, which is not the case on + Windows by default. Use `rlocationpath` instead for + cross-platform support. + + This is similar to `execpath` but strips the configuration + prefixes described above. In the example from above this means both + `empty.source` and `app` use pure workspace-relative + paths: `testapp/empty.source` and `testapp/app`. + + The `rootpath` of a file in an external repository + `repo` will start with `../repo/`, followed by the + repository-relative path. + + This has the same "one output only" requirements as `execpath`. +* `rlocationpath`: The path a built binary can pass to the `Rlocation` function of a runfiles library to find a dependency at + runtime, either in the runfiles directory (if available) or using the + runfiles manifest. + + This is similar to `rootpath` in that it does not contain + configuration prefixes, but differs in that it always starts with the + name of the repository. In the example from above this means that `empty.source` and `app` result in the following + paths: `myproject/testapp/empty.source` and `myproject/testapp/app`. + + The `rlocationpath` of a file in an external repository + `repo` will start with `repo/`, followed by the + repository-relative path. + + Passing this path to a binary and resolving it to a file system path using + the runfiles libraries is the preferred approach to find dependencies at + runtime. Compared to `rootpath`, it has the advantage that it + works on all platforms and even if the runfiles directory is not + available. + + This has the same "one output only" requirements as `execpath`. +* `location`: A synonym for either `execpath` or + `rootpath`, depending on the attribute being expanded. This is + legacy pre-Starlark behavior and not recommended unless you really know what + it does for a particular rule. See [#2475](https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016) + for details. + +`execpaths`, `rootpaths`, `rlocationpaths`, +and `locations` are the plural variations of `execpath`, +`rootpath`, `rlocationpath`, and`location`, +respectively. They support labels producing multiple outputs, in which case +each output is listed separated by a space. Zero-output rules and malformed +labels produce build errors. + +All referenced labels must appear in the consuming target's `srcs`, +output files, or `deps`. Otherwise the build fails. C++ targets can +also reference labels in `data`. + +Labels don't have to be in canonical form: `foo`, `:foo` +and `//somepkg:foo` are all fine. + +## Custom variables + +Custom "Make" variables can be referenced by any attribute marked as +*"Subject to 'Make variable' substitution"*, but only on targets that +depend on other targets that *define* these variables. + +As best practice all variables should be custom unless there's a really good +reason to bake them into core Bazel. This saves Bazel from having to load +potentially expensive dependencies to supply variables consuming tarets may +not care about. + +**C++ toolchain variables** + +The following are defined in C++ toolchain rules and available to any rule +that sets `toolchains = +["@bazel_tools//tools/cpp:current_cc_toolchain"]` +Some rules, like `java_binary`, implicitly +include the C++ toolchain in their rule definition. They inherit these variables +automatically. + +The built-in C++ rules are much more sophisticated than "run the compiler on +it". In order to support compilation modes as diverse as \*SAN, ThinLTO, +with/without modules, and carefully optimized binaries at the same time as +fast running tests on multiple platforms, the built-in rules go to great +lengths to ensure the correct inputs, outputs, and command-line flags are set +on each of potentially multiple internally generated actions. + +These variables are a fallback mechanism to be used by language experts in +rare cases. If you are tempted to use them, please [contact the Bazel devs](https://bazel.build/help) first. + +* `ABI`: The C++ ABI version. +* `AR`: The "ar" command from crosstool. +* `C_COMPILER`: + The C/C++ compiler identifier, e.g. `llvm`. +* `CC`: The C and C++ compiler command. + + We strongly recommended always using `CC_FLAGS` in + combination with `CC`. Fail to do so at your own risk. +* `CC_FLAGS`: A minimal set of flags for the C/C++ + compiler to be usable by genrules. In particular, this contains flags to + select the correct architecture if `CC` supports multiple + architectures. +* `DUMPBIN`: Microsoft COFF Binary File Dumper (dumpbin.exe) from + from Microsoft Visual Studio. +* `NM`: The "nm" command from crosstool. +* `OBJCOPY`: The objcopy command from the same suite as the C/C++ + compiler. +* `STRIP`: The strip command from the same suite as the C/C++ + compiler. + +**Java toolchain variables** + +The following are defined in Java toolchain rules and available to any rule +that sets `toolchains = +["@rules_java//toolchains:current_java_runtime"]` (or +`"@rules_java//toolchains:current_host_java_runtime"` +for the host toolchain equivalent). + +Most of the tools in the JDK should not be used directly. The built-in Java +rules use much more sophisticated approaches to Java compilation and packaging +than upstream tools can express, such as interface Jars, header interface +Jars, and highly optimized Jar packaging and merging implementations. + +These variables are a fallback mechanism to be used by language experts in +rare cases. If you are tempted to use them, please [contact the Bazel devs](https://bazel.build/help) first. + +* `JAVA`: The "java" command (a Java virtual + machine). Avoid this, and use a `java_binary` rule + instead where possible. May be a relative path. If you must change + directories before invoking `java`, you need to capture the + working directory before changing it. +* `JAVABASE`: The base directory containing the + Java utilities. May be a relative path. It will have a "bin" + subdirectory. + +**Starlark-defined variables** + +Rule and [toolchain](/docs/toolchains) writers can define +completely custom variables by returning a +[TemplateVariableInfo](/rules/lib/TemplateVariableInfo) +provider. Any rules depending on these through the +`toolchains` attribute can then read their values: + +[See an example of Starlark-defined variables](https://github.com/bazelbuild/examples/tree/main/make-variables#custom-starlark-defined-variables). \ No newline at end of file diff --git a/versions/8.6.0/reference/be/objective-c.mdx b/versions/8.6.0/reference/be/objective-c.mdx new file mode 100644 index 00000000..97ac34a5 --- /dev/null +++ b/versions/8.6.0/reference/be/objective-c.mdx @@ -0,0 +1,74 @@ +--- +title: 'Objective-C Rules' +--- + +## Rules + +* [objc_import](#objc_import) +* [objc_library](#objc_library) + +## objc_import + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/objc/objc_import.bzl) + +``` +objc_import(name, deps, hdrs, alwayslink, archives, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, includes, restricted_to, sdk_dylibs, sdk_frameworks, sdk_includes, tags, target_compatible_with, testonly, textual_hdrs, toolchains, visibility, weak_sdk_frameworks) +``` + +This rule encapsulates an already-compiled static library in the form of an +`.a` file. It also allows exporting headers and resources using the same +attributes supported by `objc_library`. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of targets that this target depend on. | +| `hdrs` | List of [labels](/concepts/labels); default is `[]` The list of C, C++, Objective-C, and Objective-C++ header files published by this library to be included by sources in dependent rules. These headers describe the public interface for the library and will be made available for inclusion by sources in this rule or in dependent rules. Headers not meant to be included by a client of this library should be listed in the srcs attribute instead. These will be compiled separately from the source if modules are enabled. | +| `alwayslink` | Boolean; default is `False` If 1, any bundle or binary that depends (directly or indirectly) on this library will link in all the object files for the files listed in `srcs` and `non_arc_srcs`, even if some contain no symbols referenced by the binary. This is useful if your code isn't explicitly called by code in the binary, e.g., if your code registers to receive some callback provided by some service. | +| `archives` | List of [labels](/concepts/labels); required The list of `.a` files provided to Objective-C targets that depend on this target. | +| `includes` | List of strings; default is `[]` List of `#include/#import` search paths to add to this target and all depending targets. This is to support third party and open-sourced libraries that do not specify the entire workspace path in their `#import/#include` statements. The paths are interpreted relative to the package directory, and the genfiles and bin roots (e.g. `blaze-genfiles/pkg/includedir` and `blaze-out/pkg/includedir`) are included in addition to the actual client root. Unlike [COPTS](/reference/be/objective-c#objc_library.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When in doubt, add "-iquote" flags to [COPTS](/reference/be/objective-c#objc_library.copts) instead. | +| `sdk_dylibs` | List of strings; default is `[]` Names of SDK .dylib libraries to link with. For instance, "libz" or "libarchive". "libc++" is included automatically if the binary has any C++ or Objective-C++ sources in its dependency tree. When linking a binary, all libraries named in that binary's transitive dependency graph are used. | +| `sdk_frameworks` | List of strings; default is `[]` Names of SDK frameworks to link with (e.g. "AddressBook", "QuartzCore"). When linking a top level Apple binary, all SDK frameworks listed in that binary's transitive dependency graph are linked. | +| `sdk_includes` | List of strings; default is `[]` List of `#include/#import` search paths to add to this target and all depending targets, where each path is relative to `$(SDKROOT)/usr/include`. | +| `textual_hdrs` | List of [labels](/concepts/labels); default is `[]` The list of C, C++, Objective-C, and Objective-C++ files that are included as headers by source files in this rule or by users of this library. Unlike hdrs, these will not be compiled separately from the sources. | +| `weak_sdk_frameworks` | List of strings; default is `[]` Names of SDK frameworks to weakly link with. For instance, "MediaAccessibility". In difference to regularly linked SDK frameworks, symbols from weakly linked frameworks do not cause an error if they are not present at runtime. | + +## objc_library + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/objc/objc_library.bzl) + +``` +objc_library(name, deps, srcs, data, hdrs, alwayslink, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, distribs, enable_modules, exec_compatible_with, exec_properties, features, implementation_deps, includes, linkopts, module_map, module_name, non_arc_srcs, pch, restricted_to, sdk_dylibs, sdk_frameworks, sdk_includes, stamp, tags, target_compatible_with, testonly, textual_hdrs, toolchains, visibility, weak_sdk_frameworks) +``` + +This rule produces a static library from the given Objective-C source files. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of targets that this target depend on. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of C, C++, Objective-C, and Objective-C++ source and header files, and/or (`.s`, `.S`, or `.asm`) assembly source files, that are processed to create the library target. These are your checked-in files, plus any generated files. Source files are compiled into .o files with Clang. Header files may be included/imported by any source or header in the srcs attribute of this target, but not by headers in hdrs or any targets that depend on this rule. Additionally, precompiled .o files may be given as srcs. Be careful to ensure consistency in the architecture of provided .o files and that of the build to avoid missing symbol linker errors. | +| `hdrs` | List of [labels](/concepts/labels); default is `[]` The list of C, C++, Objective-C, and Objective-C++ header files published by this library to be included by sources in dependent rules. These headers describe the public interface for the library and will be made available for inclusion by sources in this rule or in dependent rules. Headers not meant to be included by a client of this library should be listed in the srcs attribute instead. These will be compiled separately from the source if modules are enabled. | +| `alwayslink` | Boolean; default is `False` If 1, any bundle or binary that depends (directly or indirectly) on this library will link in all the object files for the files listed in `srcs` and `non_arc_srcs`, even if some contain no symbols referenced by the binary. This is useful if your code isn't explicitly called by code in the binary, e.g., if your code registers to receive some callback provided by some service. | +| `conlyopts` | List of strings; default is `[]` Extra flags to pass to the compiler for C files. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). These flags will only apply to this target, and not those upon which it depends, or those which depend on it. Note that for the generated Xcode project, directory paths specified using "-I" flags in copts are parsed out, prepended with "$(WORKSPACE_ROOT)/" if they are relative paths, and added to the header search paths for the associated Xcode target. | +| `copts` | List of strings; default is `[]` Extra flags to pass to the compiler. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). These flags will only apply to this target, and not those upon which it depends, or those which depend on it. Note that for the generated Xcode project, directory paths specified using "-I" flags in copts are parsed out, prepended with "$(WORKSPACE_ROOT)/" if they are relative paths, and added to the header search paths for the associated Xcode target. | +| `cxxopts` | List of strings; default is `[]` Extra flags to pass to the compiler for Objective-C++ and C++ files. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). These flags will only apply to this target, and not those upon which it depends, or those which depend on it. Note that for the generated Xcode project, directory paths specified using "-I" flags in copts are parsed out, prepended with "$(WORKSPACE_ROOT)/" if they are relative paths, and added to the header search paths for the associated Xcode target. | +| `defines` | List of strings; default is `[]` Extra `-D` flags to pass to the compiler. They should be in the form `KEY=VALUE` or simply `KEY` and are passed not only to the compiler for this target (as `copts` are) but also to all `objc_` dependers of this target. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). | +| `enable_modules` | Boolean; default is `False` Enables clang module support (via -fmodules). Setting this to 1 will allow you to @import system headers and other targets: @import UIKit; @import path_to_package_target; | +| `implementation_deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries that the library target depends on. Unlike with `deps`, the headers and include paths of these libraries (and all their transitive deps) are only used for compilation of this library, and not libraries that depend on it. Libraries specified with `implementation_deps` are still linked in binary targets that depend on this library. | +| `includes` | List of strings; default is `[]` List of `#include/#import` search paths to add to this target and all depending targets. This is to support third party and open-sourced libraries that do not specify the entire workspace path in their `#import/#include` statements. The paths are interpreted relative to the package directory, and the genfiles and bin roots (e.g. `blaze-genfiles/pkg/includedir` and `blaze-out/pkg/includedir`) are included in addition to the actual client root. Unlike [COPTS](/reference/be/objective-c#objc_library.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When in doubt, add "-iquote" flags to [COPTS](/reference/be/objective-c#objc_library.copts) instead. | +| `linkopts` | List of strings; default is `[]` Extra flags to pass to the linker. | +| `module_map` | [Label](/concepts/labels); default is `None` custom Clang module map for this target. Use of a custom module map is discouraged. Most users should use module maps generated by Bazel. If specified, Bazel will not generate a module map for this target, but will pass the provided module map to the compiler. | +| `module_name` | String; default is `""` Sets the module name for this target. By default the module name is the target path with all special symbols replaced by \_, e.g. //foo/baz:bar can be imported as foo_baz_bar. | +| `non_arc_srcs` | List of [labels](/concepts/labels); default is `[]` The list of Objective-C files that are processed to create the library target that DO NOT use ARC. The files in this attribute are treated very similar to those in the srcs attribute, but are compiled without ARC enabled. | +| `pch` | [Label](/concepts/labels); default is `None` Header file to prepend to every source file being compiled (both arc and non-arc). Use of pch files is actively discouraged in BUILD files, and this should be considered deprecated. Since pch files are not actually precompiled this is not a build-speed enhancement, and instead is just a global dependency. From a build efficiency point of view you are actually better including what you need directly in your sources where you need it. | +| `sdk_dylibs` | List of strings; default is `[]` Names of SDK .dylib libraries to link with. For instance, "libz" or "libarchive". "libc++" is included automatically if the binary has any C++ or Objective-C++ sources in its dependency tree. When linking a binary, all libraries named in that binary's transitive dependency graph are used. | +| `sdk_frameworks` | List of strings; default is `[]` Names of SDK frameworks to link with (e.g. "AddressBook", "QuartzCore"). When linking a top level Apple binary, all SDK frameworks listed in that binary's transitive dependency graph are linked. | +| `sdk_includes` | List of strings; default is `[]` List of `#include/#import` search paths to add to this target and all depending targets, where each path is relative to `$(SDKROOT)/usr/include`. | +| `stamp` | Boolean; default is `False` | +| `textual_hdrs` | List of [labels](/concepts/labels); default is `[]` The list of C, C++, Objective-C, and Objective-C++ files that are included as headers by source files in this rule or by users of this library. Unlike hdrs, these will not be compiled separately from the sources. | +| `weak_sdk_frameworks` | List of strings; default is `[]` Names of SDK frameworks to weakly link with. For instance, "MediaAccessibility". In difference to regularly linked SDK frameworks, symbols from weakly linked frameworks do not cause an error if they are not present at runtime. | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/overview.mdx b/versions/8.6.0/reference/be/overview.mdx new file mode 100644 index 00000000..4f84bccd --- /dev/null +++ b/versions/8.6.0/reference/be/overview.mdx @@ -0,0 +1,54 @@ +--- +title: 'Bazel BUILD Encyclopedia of Functions' +--- + +## Concepts and terminology + +* [Common definitions](/reference/be/common-definitions) + + [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization) + + [Label expansion](/reference/be/common-definitions#label-expansion) + + [Typical attributes for most rules](/reference/be/common-definitions#typical-attributes) + + [Common attributes for all rules](/reference/be/common-definitions#common-attributes) + + [Common attributes for tests](/reference/be/common-definitions#common-attributes-tests) + + [Common attributes for binaries](/reference/be/common-definitions#common-attributes-binaries) + + [Configurable attributes](/reference/be/common-definitions#configurable-attributes) + + [Implicit output targets](/reference/be/common-definitions#implicit-outputs) +* ["Make" variables](/reference/be/make-variables) + + [Use](/reference/be/make-variables#use) + +## Functions + +* [package](/reference/be/functions#package) +* [package_group](/reference/be/functions#package_group) +* [exports_files](/reference/be/functions#exports_files) +* [glob](/reference/be/functions#glob) +* [select](/reference/be/functions#select) +* [workspace](/rules/lib/globals/workspace#workspace) + +## Rules + +Native rules ship with the Bazel binary and do not require a `load` statement. +Native rules are available globally in BUILD files. In .bzl files, you can find them in +the `native` module. +For non-native Starlark rules that ship separately from Bazel, see the list of +[recommended rules](/rules/rules#recommended-rules). + +### Language-specific native rules + +| Language | Binary rules | Library rules | Test rules | Other rules | +| --- | --- | --- | --- | --- | +| C / C++ | [cc_binary](c-cpp#cc_binary) | [cc_import](c-cpp#cc_import) [cc_library](c-cpp#cc_library) [cc_shared_library](c-cpp#cc_shared_library) [cc_static_library](c-cpp#cc_static_library) | [cc_test](c-cpp#cc_test) | [cc_toolchain](c-cpp#cc_toolchain) [cc_toolchain_suite](c-cpp#cc_toolchain_suite) [fdo_prefetch_hints](c-cpp#fdo_prefetch_hints) [fdo_profile](c-cpp#fdo_profile) [memprof_profile](c-cpp#memprof_profile) [propeller_optimize](c-cpp#propeller_optimize) | +| Java | [java_binary](java#java_binary) | [java_import](java#java_import) [java_library](java#java_library) | [java_test](java#java_test) | [java_package_configuration](java#java_package_configuration) [java_plugin](java#java_plugin) [java_runtime](java#java_runtime) [java_toolchain](java#java_toolchain) | +| Objective-C | | [objc_import](objective-c#objc_import) [objc_library](objective-c#objc_library) | | | +| Protocol Buffer | | [cc_proto_library](protocol-buffer#cc_proto_library) [java_lite_proto_library](protocol-buffer#java_lite_proto_library) [java_proto_library](protocol-buffer#java_proto_library) [proto_library](protocol-buffer#proto_library) [py_proto_library](protocol-buffer#py_proto_library) | | [proto_lang_toolchain](protocol-buffer#proto_lang_toolchain) [proto_toolchain](protocol-buffer#proto_toolchain) | +| Python | [py_binary](python#py_binary) | [py_library](python#py_library) | [py_test](python#py_test) | [py_runtime](python#py_runtime) | +| Shell | [sh_binary](shell#sh_binary) | [sh_library](shell#sh_library) | [sh_test](shell#sh_test) | | + +### Language-agnostic native rules + +| Family | Rules | +| --- | --- | +| Extra Actions | * [action_listener](extra-actions#action_listener)* [extra_action](extra-actions#extra_action) | +| General | * [alias](general#alias)* [config_setting](general#config_setting)* [filegroup](general#filegroup)* [genquery](general#genquery)* [genrule](general#genrule)* [starlark_doc_extract](general#starlark_doc_extract)* [test_suite](general#test_suite) | +| Platforms and Toolchains | * [constraint_setting](platforms-and-toolchains#constraint_setting)* [constraint_value](platforms-and-toolchains#constraint_value)* [platform](platforms-and-toolchains#platform)* [toolchain](platforms-and-toolchains#toolchain)* [toolchain_type](platforms-and-toolchains#toolchain_type) | +| Workspace | * [bind](workspace#bind)* [local_repository](workspace#local_repository)* [new_local_repository](workspace#new_local_repository) | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/platforms-and-toolchains.mdx b/versions/8.6.0/reference/be/platforms-and-toolchains.mdx new file mode 100644 index 00000000..58d8f97f --- /dev/null +++ b/versions/8.6.0/reference/be/platforms-and-toolchains.mdx @@ -0,0 +1,356 @@ +--- +title: 'Platforms and Toolchains Rules' +--- + +This set of rules exists to allow you to model specific hardware platforms you are +building for and specify the specific tools you may need to compile code for those platforms. +The user should be familiar with the concepts explained [here](/extending/platforms). + +## Rules + +* [constraint_setting](#constraint_setting) +* [constraint_value](#constraint_value) +* [platform](#platform) +* [toolchain](#toolchain) +* [toolchain_type](#toolchain_type) + +## constraint_setting + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/platform/ConstraintSettingRule.java) + +``` +constraint_setting(name, default_constraint_value, deprecation, distribs, features, licenses, tags, testonly, visibility) +``` + +This rule is used to introduce a new constraint type for which a platform may specify a value. +For instance, you might define a `constraint_setting` named "glibc_version" to represent +the capability for platforms to have different versions of the glibc library installed. +For more details, see the +[Platforms](https://bazel.build/docs/platforms) page. + +Each `constraint_setting` has an extensible set of associated +`constraint_value`s. Usually these are defined in the same package, but sometimes a +different package will introduce new values for an existing setting. For instance, the predefined +setting `@platforms//cpu:cpu` can be extended with a custom value in order to +define a platform targeting an obscure cpu architecture. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `default_constraint_value` | [Name](/concepts/labels#target-names); [nonconfigurable](common-definitions#configurable-attributes); default is `None` The label of the default value for this setting, to be used if no value is given. If this attribute is present, the `constraint_value` it points to must be defined in the same package as this `constraint_setting`. If a constraint setting has a default value, then whenever a platform does not include any constraint value for that setting, it is the same as if the platform had specified the default value. Otherwise, if there is no default value, the constraint setting is considered to be unspecified by that platform. In that case, the platform would not match against any constraint list (such as for a `config_setting`) that requires a particular value for that setting. | + +## constraint_value + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/platform/ConstraintValueRule.java) + +``` +constraint_value(name, constraint_setting, deprecation, distribs, features, licenses, tags, testonly, visibility) +``` + +This rule introduces a new value for a given constraint type. +For more details, see the +[Platforms](https://bazel.build/docs/platforms) page. + +#### Example + +The following creates a new possible value for the predefined `constraint_value` +representing cpu architecture. + +``` +constraint_value( + name = "mips", + constraint_setting = "@platforms//cpu:cpu", +) +``` + +Platforms can then declare that they have the `mips` architecture as an alternative to +`x86_64`, `arm`, and so on. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `constraint_setting` | [Label](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); required The `constraint_setting` for which this `constraint_value` is a possible choice. | + +## platform + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/platform/PlatformRule.java) + +``` +platform(name, constraint_values, deprecation, distribs, exec_properties, features, flags, licenses, missing_toolchain_error, parents, remote_execution_properties, required_settings, tags, testonly, visibility) +``` + +This rule defines a new platform -- a named collection of constraint choices +(such as cpu architecture or compiler version) describing an environment in +which part of the build may run. +For more details, see the [Platforms](/extending/platforms) page. + +#### Example + +This defines a platform that describes any environment running Linux on ARM. + +``` +platform( + name = "linux_arm", + constraint_values = [ + "@platforms//os:linux", + "@platforms//cpu:arm", + ], +) +``` + +### Platform Flags + +Platforms may use the `flags` attribute to specify a list of flags that will be added +to the configuration whenever the platform is used as the target platform (i.e., as the value of +the `--platforms` flag). + +Flags set from the platform effectively have the highest precedence and overwrite any previous +value for that flag, from the command line, rc file, or transition. + +#### Example + +``` +platform( + name = "foo", + flags = [ + "--dynamic_mode=fully", + "--//bool_flag", + "--no//package:other_bool_flag", + ], +) +``` + +This defines a platform named `foo`. When this is the target platform (either because +the user specified `--platforms//:foo`, because a transition set the +`//command_line_option:platforms` flag to `["//:foo"]`, or because +`//:foo` was used as an execution platform), then the given flags will be set in the +configuration. + +#### Platforms and Repeatable Flags + +Some flags will accumulate values when they are repeated, such as `--features`, +`--copt`, any Starlark flag created as `config.string(repeatable = True)`. +These flags are not compatible with setting the flags from the platform: instead, all previous +values will be removed and overwritten with the values from the platform. + +As an example, given the following platform, the invocation `build --platforms=//:repeat_demo +--features feature_a --features feature_b` will end up with the value of the +`--feature` flag being `["feature_c", "feature_d"]`, removing the features +set on the command line. + +``` +platform( + name = "repeat_demo", + flags = [ + "--features=feature_c", + "--features=feature_d", + ], +) +``` + +For this reason, it is discouraged to use repeatable flags in the `flags` attribute. + +### Platform Inheritance + +Platforms may use the `parents` attribute to specify another platform that they will +inherit constraint values from. Although the `parents` attribute takes a list, no +more than a single value is currently supported, and specifying multiple parents is an error. + +When checking for the value of a constraint setting in a platform, first the values directly set +(via the `constraint_values` attribute) are checked, and then the constraint values on +the parent. This continues recursively up the chain of parent platforms. In this manner, any +values set directly on a platform will override the values set on the parent. + +Platforms inherit the `exec_properties` attribute from the parent platform. +The dictionary entries in `exec_properties` of the parent and child platforms +will be combined. +If the same key appears in both the parent's and the child's `exec_properties`, +the child's value will be used. If the child platform specifies an empty string as a value, the +corresponding property will be unset. + +Platforms can also inherit the (deprecated) `remote_execution_properties` attribute +from the parent platform. Note: new code should use `exec_properties` instead. The +logic described below is maintained to be compatible with legacy behavior but will be removed +in the future. +The logic for setting the `remote_execution_platform` is as follows when there +is a parent platform: + +1. If `remote_execution_property` is not set on the child platform, the parent's + `remote_execution_properties` will be used. +2. If `remote_execution_property` is set on the child platform, and contains the + literal string {PARENT_REMOTE_EXECUTION_PROPERTIES}, that macro will be + replaced with the contents of the parent's `remote_execution_property` attribute. +3. If `remote_execution_property` is set on the child platform, and does not contain + the macro, the child's `remote_execution_property` will be used unchanged. + +*Since `remote_execution_properties` is deprecated and will be phased out, mixing +`remote_execution_properties` and `exec_properties` in the same +inheritance chain is not allowed.* +Prefer to use `exec_properties` over the deprecated +`remote_execution_properties`. + +#### Example: Constraint Values + +``` +platform( + name = "parent", + constraint_values = [ + "@platforms//os:linux", + "@platforms//cpu:arm", + ], +) +platform( + name = "child_a", + parents = [":parent"], + constraint_values = [ + "@platforms//cpu:x86_64", + ], +) +platform( + name = "child_b", + parents = [":parent"], +) +``` + +In this example, the child platforms have the following properties: + +* `child_a` has the constraint values `@platforms//os:linux` (inherited + from the parent) and `@platforms//cpu:x86_64` (set directly on the platform). +* `child_b` inherits all constraint values from the parent, and doesn't set any of + its own. + +#### Example: Execution properties + +``` +platform( + name = "parent", + exec_properties = { + "k1": "v1", + "k2": "v2", + }, +) +platform( + name = "child_a", + parents = [":parent"], +) +platform( + name = "child_b", + parents = [":parent"], + exec_properties = { + "k1": "child" + } +) +platform( + name = "child_c", + parents = [":parent"], + exec_properties = { + "k1": "" + } +) +platform( + name = "child_d", + parents = [":parent"], + exec_properties = { + "k3": "v3" + } +) +``` + +In this example, the child platforms have the following properties: + +* `child_a` inherits the "exec_properties" of the parent and does not set its own. +* `child_b` inherits the parent's `exec_properties` and overrides the + value of `k1`. Its `exec_properties` will be: + `{ "k1": "child", "k2": "v2" }`. +* `child_c` inherits the parent's `exec_properties` and unsets + `k1`. Its `exec_properties` will be: + `{ "k2": "v2" }`. +* `child_d` inherits the parent's `exec_properties` and adds a new + property. Its `exec_properties` will be: + `{ "k1": "v1", "k2": "v2", "k3": "v3" }`. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `constraint_values` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` The combination of constraint choices that this platform comprises. In order for a platform to apply to a given environment, the environment must have at least the values in this list. Each `constraint_value` in this list must be for a different `constraint_setting`. For example, you cannot define a platform that requires the cpu architecture to be both `@platforms//cpu:x86_64` and `@platforms//cpu:arm`. | +| `exec_properties` | Dictionary: String -> String; [nonconfigurable](common-definitions#configurable-attributes); default is `{}` A map of strings that affect the way actions are executed remotely. Bazel makes no attempt to interpret this, it is treated as opaque data that's forwarded via the Platform field of the [remote execution protocol](https://github.com/bazelbuild/remote-apis). This includes any data from the parent platform's `exec_properties` attributes. If the child and parent platform define the same keys, the child's values are kept. Any keys associated with a value that is an empty string are removed from the dictionary. This attribute is a full replacement for the deprecated `remote_execution_properties`. | +| `flags` | List of strings; [nonconfigurable](common-definitions#configurable-attributes); default is `[]` A list of flags that will be enabled when this platform is used as the target platform in a configuration. Only flags that can be set in transitions are allowed to be used. | +| `missing_toolchain_error` | String; [nonconfigurable](common-definitions#configurable-attributes); default is `"For more information on platforms or toolchains see https://bazel.build/concepts/platforms-intro."` A custom error message that is displayed when a mandatory toolchain requirement cannot be satisfied for this target platform. Intended to point to relevant documentation users can read to understand why their toolchains are misconfigured. Not inherited from parent platforms. | +| `parents` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` The label of a `platform` target that this platform should inherit from. Although the attribute takes a list, there should be no more than one platform present. Any constraint_settings not set directly on this platform will be found in the parent platform. See the section on [Platform Inheritance](#platform_inheritance) for details. | +| `remote_execution_properties` | String; [nonconfigurable](common-definitions#configurable-attributes); default is `""` DEPRECATED. Please use exec_properties attribute instead. A string used to configure a remote execution platform. Actual builds make no attempt to interpret this, it is treated as opaque data that can be used by a specific SpawnRunner. This can include data from the parent platform's "remote_execution_properties" attribute, by using the macro "{PARENT_REMOTE_EXECUTION_PROPERTIES}". See the section on [Platform Inheritance](#platform_inheritance) for details. | +| `required_settings` | List of [labels](/concepts/labels); default is `[]` A list of `config_setting`s that must be satisfied by the target configuration in order for this platform to be used as an execution platform during toolchain resolution. Required settings are not inherited from parent platforms. | + +## toolchain + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/platform/ToolchainRule.java) + +``` +toolchain(name, deprecation, distribs, exec_compatible_with, features, licenses, tags, target_compatible_with, target_settings, testonly, toolchain, toolchain_type, use_target_platform_constraints, visibility) +``` + +This rule declares a specific toolchain's type and constraints so that it can be selected +during toolchain resolution. See the +[Toolchains](https://bazel.build/docs/toolchains) page for more +details. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `exec_compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` A list of `constraint_value`s that must be satisfied by an execution platform in order for this toolchain to be selected for a target building on that platform. | +| `target_compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` A list of `constraint_value`s that must be satisfied by the target platform in order for this toolchain to be selected for a target building for that platform. | +| `target_settings` | List of [labels](/concepts/labels); default is `[]` A list of `config_setting`s that must be satisfied by the target configuration in order for this toolchain to be selected during toolchain resolution. | +| `toolchain` | [Name](/concepts/labels#target-names); required The target representing the actual tool or tool suite that is made available when this toolchain is selected. | +| `toolchain_type` | [Label](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); required The label of a `toolchain_type` target that represents the role that this toolchain serves. | +| `use_target_platform_constraints` | Boolean; [nonconfigurable](common-definitions#configurable-attributes); default is `False` If `True`, this toolchain behaves as if its `exec_compatible_with` and `target_compatible_with` constraints are set to those of the current target platform. `exec_compatible_with` and `target_compatible_with` must not be set in that case. | + +## toolchain_type + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/ToolchainType.java) + +``` +toolchain_type(name, compatible_with, deprecation, features, no_match_error, restricted_to, tags, target_compatible_with, testonly, visibility) +``` + +This rule defines a new type of toolchain -- a simple target that represents a class of tools that +serve the same role for different platforms. + +See the [Toolchains](/docs/toolchains) page for more details. + +#### Example + +This defines a toolchain type for a custom rule. + +``` +toolchain_type( + name = "bar_toolchain_type", +) +``` + +This can be used in a bzl file. + +``` +bar_binary = rule( + implementation = _bar_binary_impl, + attrs = { + "srcs": attr.label_list(allow_files = True), + ... + # No `_compiler` attribute anymore. + }, + toolchains = ["//bar_tools:toolchain_type"] +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `no_match_error` | String; [nonconfigurable](common-definitions#configurable-attributes); default is `""` A custom error message to display when no matching toolchain is found for this type. | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/protocol-buffer.mdx b/versions/8.6.0/reference/be/protocol-buffer.mdx new file mode 100644 index 00000000..17fdbcc2 --- /dev/null +++ b/versions/8.6.0/reference/be/protocol-buffer.mdx @@ -0,0 +1,278 @@ +--- +title: 'Protocol Buffer Rules' +--- + +## Rules + +* [cc_proto_library](#cc_proto_library) +* [java_lite_proto_library](#java_lite_proto_library) +* [java_proto_library](#java_proto_library) +* [proto_library](#proto_library) +* [py_proto_library](#py_proto_library) +* [proto_lang_toolchain](#proto_lang_toolchain) +* [proto_toolchain](#proto_toolchain) + +## cc_proto_library + +[View rule sourceopen_in_new](https://github.com/protocolbuffers/protobuf/tree/v29.0-rc2/bazel/private/bazel_cc_proto_library.bzl) + +``` +cc_proto_library(name, deps, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +`cc_proto_library` generates C++ code from `.proto` files. + +`deps` must point to [`proto_library`](protocol-buffer#proto_library) rules. + +Example: + +``` +cc_library( + name = "lib", + deps = [":foo_cc_proto"], +) + +cc_proto_library( + name = "foo_cc_proto", + deps = [":foo_proto"], +) + +proto_library( + name = "foo_proto", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of [`proto_library`](protocol-buffer#proto_library) rules to generate C++ code for. | + +## java_lite_proto_library + +[View rule sourceopen_in_new](https://github.com/protocolbuffers/protobuf/tree/v29.0-rc2/bazel/private/java_lite_proto_library.bzl) + +``` +java_lite_proto_library(name, deps, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +`java_lite_proto_library` generates Java code from `.proto` files. + +`deps` must point to [`proto_library`](protocol-buffer#proto_library) rules. + +Example: + +``` +java_library( + name = "lib", + runtime_deps = [":foo"], +) + +java_lite_proto_library( + name = "foo", + deps = [":bar"], +) + +proto_library( + name = "bar", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of [`proto_library`](protocol-buffer#proto_library) rules to generate Java code for. | + +## java_proto_library + +[View rule sourceopen_in_new](https://github.com/protocolbuffers/protobuf/tree/v29.0-rc2/bazel/private/bazel_java_proto_library_rule.bzl) + +``` +java_proto_library(name, deps, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, licenses, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +`java_proto_library` generates Java code from `.proto` files. + +`deps` must point to [`proto_library`](protocol-buffer#proto_library) rules. + +Example: + +``` +java_library( + name = "lib", + runtime_deps = [":foo_java_proto"], +) + +java_proto_library( + name = "foo_java_proto", + deps = [":foo_proto"], +) + +proto_library( + name = "foo_proto", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of [`proto_library`](protocol-buffer#proto_library) rules to generate Java code for. | + +## proto_library + +[View rule sourceopen_in_new](https://github.com/protocolbuffers/protobuf/tree/v29.0-rc2/bazel/private/bazel_proto_library_rule.bzl) + +``` +proto_library(name, deps, srcs, data, allow_exports, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, exports, features, import_prefix, licenses, restricted_to, strip_import_prefix, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +If using Bazel, please load the rule from https://github.com/bazelbuild/rules_proto. + +Use `proto_library` to define libraries of protocol buffers which +may be used from multiple languages. A `proto_library` may be listed +in the `deps` clause of supported rules, such as +`java_proto_library`. + +When compiled on the command-line, a `proto_library` creates a file +named `foo-descriptor-set.proto.bin`, which is the descriptor set for +the messages the rule srcs. The file is a serialized +`FileDescriptorSet`, which is described in +https://developers.google.com/protocol-buffers/docs/techniques#self-description. + +It only contains information about the `.proto` files directly +mentioned by a `proto_library` rule; the collection of transitive +descriptor sets is available through the +`[ProtoInfo].transitive_descriptor_sets` Starlark provider. +See documentation in `proto_info.bzl`. + +Recommended code organization: + +* One `proto_library` rule per `.proto` file.* A file named `foo.proto` will be in a rule named `foo_proto`, + which is located in the same package.* A `[language]_proto_library` that wraps a `proto_library` + named `foo_proto` should be called `foo_[language]_proto`, + and be located in the same package. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other `proto_library` rules that the target depends upon. A `proto_library` may only depend on other `proto_library` targets. It may not depend on language-specific libraries. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of `.proto` and `.protodevel` files that are processed to create the target. This is usually a non empty list. One usecase where `srcs` can be empty is an *alias-library*. This is a proto_library rule having one or more other proto_library in `deps`. This pattern can be used to e.g. export a public api under a persistent name. | +| `allow_exports` | [Label](/concepts/labels); default is `None` An optional allowlist that prevents proto library to be reexported or used in lang_proto_library that is not in one of the listed packages. | +| `exports` | List of [labels](/concepts/labels); default is `[]` List of proto_library targets that can be referenced via "import public" in the proto source. It's an error if you use "import public" but do not list the corresponding library in the exports attribute. Note that you have list the library both in deps and exports since not all lang_proto_library implementations have been changed yet. | +| `import_prefix` | String; default is `""` The prefix to add to the paths of the .proto files in this rule. When set, the .proto source files in the `srcs` attribute of this rule are accessible at is the value of this attribute prepended to their repository-relative path. The prefix in the `strip_import_prefix` attribute is removed before this prefix is added. | +| `strip_import_prefix` | String; default is `"/"` The prefix to strip from the paths of the .proto files in this rule. When set, .proto source files in the `srcs` attribute of this rule are accessible at their path with this prefix cut off. If it's a relative path (not starting with a slash), it's taken as a package-relative one. If it's an absolute one, it's understood as a repository-relative path. The prefix in the `import_prefix` attribute is added after this prefix is stripped. | + +## py_proto_library + +[View rule sourceopen_in_new](https://github.com/protocolbuffers/protobuf/tree/v29.0-rc2/bazel/py_proto_library.bzl) + +``` +py_proto_library(name, deps, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +Use `py_proto_library` to generate Python libraries from `.proto` files. +The convention is to name the `py_proto_library` rule `foo_py_pb2`, +when it is wrapping `proto_library` rule `foo_proto`. +`deps` must point to a `proto_library` rule. +Example: +```starlark +py_library( +name = "lib", +deps = [":foo_py_pb2"], +) +py_proto_library( +name = "foo_py_pb2", +deps = [":foo_proto"], +) +proto_library( +name = "foo_proto", +srcs = ["foo.proto"], +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of `proto_library` rules to generate Python libraries for. Usually this is just the one target: the proto library of interest. It can be any target providing `ProtoInfo`. | + +## proto_lang_toolchain + +[View rule sourceopen_in_new](https://github.com/protocolbuffers/protobuf/tree/v29.0-rc2/bazel/private/proto_lang_toolchain_rule.bzl) + +``` +proto_lang_toolchain(name, allowlist_different_package, blacklisted_protos, command_line, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, mnemonic, output_files, plugin, plugin_format_flag, progress_message, protoc_minimal_do_not_use, restricted_to, runtime, tags, target_compatible_with, testonly, toolchain_type, toolchains, visibility) +``` + +If using Bazel, please load the rule from https://github.com/bazelbuild/rules_proto. + +Specifies how a LANG_proto_library rule (e.g., `java_proto_library`) should invoke the +proto-compiler. +Some LANG_proto_library rules allow specifying which toolchain to use using command-line flags; +consult their documentation. + +Normally you should not write those kind of rules unless you want to +tune your Java compiler. + +There's no compiler. The proto-compiler is taken from the proto_library rule we attach to. It is +passed as a command-line flag to Blaze. +Several features require a proto-compiler to be invoked on the proto_library rule itself. +It's beneficial to enforce the compiler that LANG_proto_library uses is the same as the one +`proto_library` does. + +#### Examples + +A simple example would be: + +``` +proto_lang_toolchain( + name = "javalite_toolchain", + command_line = "--javalite_out=shared,immutable:$(OUT)", + plugin = ":javalite_plugin", + runtime = ":protobuf_lite", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `allowlist_different_package` | [Label](/concepts/labels); default is `None` | +| `blacklisted_protos` | List of [labels](/concepts/labels); default is `[]` No code will be generated for files in the `srcs` attribute of `blacklisted_protos`. This is used for .proto files that are already linked into proto runtimes, such as `any.proto`. | +| `command_line` | String; required This value will be passed to proto-compiler to generate the code. Only include the parts specific to this code-generator/plugin (e.g., do not include -I parameters) * `$(OUT)` is LANG_proto_library-specific. The rules are expected to define how they interpret this variable. For Java, for example, $(OUT) will be replaced with the src-jar filename to create. | +| `mnemonic` | String; default is `"GenProto"` This value will be set as the mnemonic on protoc action. | +| `output_files` | String; default is `"legacy"` Controls how `$(OUT)` in `command_line` is formatted, either by a path to a single file or output directory in case of multiple files. Possible values are: "single", "multiple". | +| `plugin` | [Label](/concepts/labels); default is `None` If provided, will be made available to the action that calls the proto-compiler, and will be passed to the proto-compiler: `--plugin=protoc-gen-PLUGIN=<executable>.` | +| `plugin_format_flag` | String; default is `""` If provided, this value will be passed to proto-compiler to use the plugin. The value must contain a single %s which is replaced with plugin executable. `--plugin=protoc-gen-PLUGIN=<executable>.` | +| `progress_message` | String; default is `"Generating proto_library %{label}"` This value will be set as the progress message on protoc action. | +| `protoc_minimal_do_not_use` | [Label](/concepts/labels); default is `None` | +| `runtime` | [Label](/concepts/labels); default is `None` A language-specific library that the generated code is compiled against. The exact behavior is LANG_proto_library-specific. Java, for example, should compile against the runtime. | +| `toolchain_type` | [Label](/concepts/labels); default is `None` | + +## proto_toolchain + +[View rule sourceopen_in_new](https://github.com/protocolbuffers/protobuf/tree/v29.0-rc2/bazel/private/proto_toolchain_rule.bzl) + +``` +proto_toolchain(name, command_line, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, mnemonic, output_files, progress_message, proto_compiler, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `command_line` | String; default is `"--descriptor_set_out=%s"` | +| `mnemonic` | String; default is `"GenProtoDescriptorSet"` | +| `output_files` | String; default is `"single"` | +| `progress_message` | String; default is `"Generating Descriptor Set proto_library %{label}"` | +| `proto_compiler` | [Label](/concepts/labels); default is `None` | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/python.mdx b/versions/8.6.0/reference/be/python.mdx new file mode 100644 index 00000000..bbdb5471 --- /dev/null +++ b/versions/8.6.0/reference/be/python.mdx @@ -0,0 +1,153 @@ +--- +title: 'Python Rules' +--- + +## Rules + +* [py_binary](#py_binary) +* [py_library](#py_library) +* [py_test](#py_test) +* [py_runtime](#py_runtime) + +## py_binary + +[View rule sourceopen_in_new](https://github.com/bazelbuild/rules_python/tree/0.40.0/python/private/py_binary_rule.bzl) + +``` +py_binary(name, deps, srcs, data, args, compatible_with, deprecation, distribs, env, exec_compatible_with, exec_properties, features, imports, legacy_create_init, licenses, main, output_licenses, precompile, precompile_invalidation_mode, precompile_optimize_level, precompile_source_retention, pyc_collection, python_version, restricted_to, srcs_version, stamp, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` List of additional libraries to be linked in to the target. See comments about the [`deps` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). These are typically `py_library` rules. Targets that only provide data files used at runtime belong in the `data` attribute. | +| `srcs` | List of [labels](/concepts/labels); required The list of Python source files that are processed to create the target. This includes all your checked-in code and may include generated source files. The `.py` files belong in `srcs` and library targets belong in `deps`. Other binary files that may be needed at run time belong in `data`. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files need by this library at runtime. See comments about the [`data` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). There is no `py_embed_data` like there is `cc_embed_data` and `go_embed_data`. This is because Python has a concept of runtime resources. | +| `imports` | List of strings; default is `[]` List of import directories to be added to the PYTHONPATH. Subject to "Make variable" substitution. These import directories will be added for this rule and all rules that depend on it (note: not the rules this rule depends on. Each directory will be added to `PYTHONPATH` by `py_binary` rules that depend on this rule. The strings are repo-runfiles-root relative, Absolute paths (paths that start with `/`) and paths that references a path above the execution root are not allowed and will result in an error. | +| `legacy_create_init` | Integer; default is `-1` Whether to implicitly create empty `\__init\_\_.py` files in the runfiles tree. These are created in every directory containing Python source code or shared libraries, and every parent directory of those directories, excluding the repo root directory. The default, `-1` (auto), means true unless `--incompatible_default_to_explicit_init_py` is used. If false, the user is responsible for creating (possibly empty) `\__init\_\_.py` files and adding them to the `srcs` of Python targets as required. | +| `main` | [Label](/concepts/labels); default is `None` Optional; the name of the source file that is the main entry point of the application. This file must also be listed in `srcs`. If left unspecified, `name`, with `.py` appended, is used instead. If `name` does not match any filename in `srcs`, `main` must be specified. | +| `precompile` | String; default is `"inherit"` Whether py source files \*\*for this target\*\* should be precompiled. Values: \* `inherit`: Allow the downstream binary decide if precompiled files are used. \* `enabled`: Compile Python source files at build time. \* `disabled`: Don't compile Python source files at build time. :::{seealso} \* The {flag}`--precompile` flag, which can override this attribute in some cases and will affect all targets when building. \* The {obj}`pyc_collection` attribute for transitively enabling precompiling on a per-target basis. \* The [Precompiling](precompiling) docs for a guide about using precompiling. ::: | +| `precompile_invalidation_mode` | String; default is `"auto"` How precompiled files should be verified to be up-to-date with their associated source files. Possible values are: \* `auto`: The effective value will be automatically determined by other build settings. \* `checked_hash`: Use the pyc file if the hash of the source file matches the hash recorded in the pyc file. This is most useful when working with code that you may modify. \* `unchecked_hash`: Always use the pyc file; don't check the pyc's hash against the source file. This is most useful when the code won't be modified. For more information on pyc invalidation modes, see https://docs.python.org/3/library/py_compile.html#py_compile.PycInvalidationMode | +| `precompile_optimize_level` | Integer; default is `0` The optimization level for precompiled files. For more information about optimization levels, see the `compile()` function's `optimize` arg docs at https://docs.python.org/3/library/functions.html#compile NOTE: The value `-1` means "current interpreter", which will be the interpreter used \_at build time when pycs are generated\_, not the interpreter used at runtime when the code actually runs. | +| `precompile_source_retention` | String; default is `"inherit"` Determines, when a source file is compiled, if the source file is kept in the resulting output or not. Valid values are: \* `inherit`: Inherit the value from the {flag}`--precompile_source_retention` flag. \* `keep_source`: Include the original Python source. \* `omit_source`: Don't include the original py source. | +| `pyc_collection` | String; default is `"inherit"` Determines whether pyc files from dependencies should be manually included. Valid values are: \* `inherit`: Inherit the value from {flag}`--precompile`. \* `include_pyc`: Add implicitly generated pyc files from dependencies. i.e. pyc files for targets that specify {attr}`precompile="inherit"`. \* `disabled`: Don't add implicitly generated pyc files. Note that pyc files may still come from dependencies that enable precompiling at the target level. | +| `python_version` | String; default is `"PY3"` Defunct, unused, does nothing. | +| `srcs_version` | String; default is `"PY2AND3"` Defunct, unused, does nothing. | +| `stamp` | Integer; default is `-1` Whether to encode build information into the binary. Possible values: \* `stamp = 1`: Always stamp the build information into the binary, even in `--nostamp` builds. \*\*This setting should be avoided\*\*, since it potentially kills remote caching for the binary and any downstream actions that depend on it. \* `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` flag. Stamped binaries are not rebuilt unless their dependencies change. WARNING: Stamping can harm build performance by reducing cache hits and should be avoided if possible. | + +## py_library + +[View rule sourceopen_in_new](https://github.com/bazelbuild/rules_python/tree/0.40.0/python/private/py_library_rule.bzl) + +``` +py_library(name, deps, srcs, data, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, imports, licenses, precompile, precompile_invalidation_mode, precompile_optimize_level, precompile_source_retention, restricted_to, srcs_version, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +A library of Python code that can be depended upon. +Default outputs: +\* The input Python sources +\* The precompiled artifacts from the sources. +NOTE: Precompilation affects which of the default outputs are included in the +resulting runfiles. See the precompile-related attributes and flags for +more information. +:::{versionchanged} 0.37.0 +Source files are no longer added to the runfiles directly. +::: + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` List of additional libraries to be linked in to the target. See comments about the [`deps` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). These are typically `py_library` rules. Targets that only provide data files used at runtime belong in the `data` attribute. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of Python source files that are processed to create the target. This includes all your checked-in code and may include generated source files. The `.py` files belong in `srcs` and library targets belong in `deps`. Other binary files that may be needed at run time belong in `data`. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files need by this library at runtime. See comments about the [`data` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). There is no `py_embed_data` like there is `cc_embed_data` and `go_embed_data`. This is because Python has a concept of runtime resources. | +| `imports` | List of strings; default is `[]` List of import directories to be added to the PYTHONPATH. Subject to "Make variable" substitution. These import directories will be added for this rule and all rules that depend on it (note: not the rules this rule depends on. Each directory will be added to `PYTHONPATH` by `py_binary` rules that depend on this rule. The strings are repo-runfiles-root relative, Absolute paths (paths that start with `/`) and paths that references a path above the execution root are not allowed and will result in an error. | +| `precompile` | String; default is `"inherit"` Whether py source files \*\*for this target\*\* should be precompiled. Values: \* `inherit`: Allow the downstream binary decide if precompiled files are used. \* `enabled`: Compile Python source files at build time. \* `disabled`: Don't compile Python source files at build time. :::{seealso} \* The {flag}`--precompile` flag, which can override this attribute in some cases and will affect all targets when building. \* The {obj}`pyc_collection` attribute for transitively enabling precompiling on a per-target basis. \* The [Precompiling](precompiling) docs for a guide about using precompiling. ::: | +| `precompile_invalidation_mode` | String; default is `"auto"` How precompiled files should be verified to be up-to-date with their associated source files. Possible values are: \* `auto`: The effective value will be automatically determined by other build settings. \* `checked_hash`: Use the pyc file if the hash of the source file matches the hash recorded in the pyc file. This is most useful when working with code that you may modify. \* `unchecked_hash`: Always use the pyc file; don't check the pyc's hash against the source file. This is most useful when the code won't be modified. For more information on pyc invalidation modes, see https://docs.python.org/3/library/py_compile.html#py_compile.PycInvalidationMode | +| `precompile_optimize_level` | Integer; default is `0` The optimization level for precompiled files. For more information about optimization levels, see the `compile()` function's `optimize` arg docs at https://docs.python.org/3/library/functions.html#compile NOTE: The value `-1` means "current interpreter", which will be the interpreter used \_at build time when pycs are generated\_, not the interpreter used at runtime when the code actually runs. | +| `precompile_source_retention` | String; default is `"inherit"` Determines, when a source file is compiled, if the source file is kept in the resulting output or not. Valid values are: \* `inherit`: Inherit the value from the {flag}`--precompile_source_retention` flag. \* `keep_source`: Include the original Python source. \* `omit_source`: Don't include the original py source. | +| `srcs_version` | String; default is `"PY2AND3"` Defunct, unused, does nothing. | + +## py_test + +[View rule sourceopen_in_new](https://github.com/bazelbuild/rules_python/tree/0.40.0/python/private/py_test_rule.bzl) + +``` +py_test(name, deps, srcs, data, args, compatible_with, deprecation, distribs, env, env_inherit, exec_compatible_with, exec_properties, features, flaky, imports, legacy_create_init, licenses, local, main, precompile, precompile_invalidation_mode, precompile_optimize_level, precompile_source_retention, pyc_collection, python_version, restricted_to, shard_count, size, srcs_version, stamp, tags, target_compatible_with, testonly, timeout, toolchains, visibility) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` List of additional libraries to be linked in to the target. See comments about the [`deps` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). These are typically `py_library` rules. Targets that only provide data files used at runtime belong in the `data` attribute. | +| `srcs` | List of [labels](/concepts/labels); required The list of Python source files that are processed to create the target. This includes all your checked-in code and may include generated source files. The `.py` files belong in `srcs` and library targets belong in `deps`. Other binary files that may be needed at run time belong in `data`. | +| `data` | List of [labels](/concepts/labels); default is `[]` The list of files need by this library at runtime. See comments about the [`data` attribute typically defined by rules](https://bazel.build/reference/be/common-definitions#typical-attributes). There is no `py_embed_data` like there is `cc_embed_data` and `go_embed_data`. This is because Python has a concept of runtime resources. | +| `imports` | List of strings; default is `[]` List of import directories to be added to the PYTHONPATH. Subject to "Make variable" substitution. These import directories will be added for this rule and all rules that depend on it (note: not the rules this rule depends on. Each directory will be added to `PYTHONPATH` by `py_binary` rules that depend on this rule. The strings are repo-runfiles-root relative, Absolute paths (paths that start with `/`) and paths that references a path above the execution root are not allowed and will result in an error. | +| `legacy_create_init` | Integer; default is `-1` Whether to implicitly create empty `\__init\_\_.py` files in the runfiles tree. These are created in every directory containing Python source code or shared libraries, and every parent directory of those directories, excluding the repo root directory. The default, `-1` (auto), means true unless `--incompatible_default_to_explicit_init_py` is used. If false, the user is responsible for creating (possibly empty) `\__init\_\_.py` files and adding them to the `srcs` of Python targets as required. | +| `main` | [Label](/concepts/labels); default is `None` Optional; the name of the source file that is the main entry point of the application. This file must also be listed in `srcs`. If left unspecified, `name`, with `.py` appended, is used instead. If `name` does not match any filename in `srcs`, `main` must be specified. | +| `precompile` | String; default is `"inherit"` Whether py source files \*\*for this target\*\* should be precompiled. Values: \* `inherit`: Allow the downstream binary decide if precompiled files are used. \* `enabled`: Compile Python source files at build time. \* `disabled`: Don't compile Python source files at build time. :::{seealso} \* The {flag}`--precompile` flag, which can override this attribute in some cases and will affect all targets when building. \* The {obj}`pyc_collection` attribute for transitively enabling precompiling on a per-target basis. \* The [Precompiling](precompiling) docs for a guide about using precompiling. ::: | +| `precompile_invalidation_mode` | String; default is `"auto"` How precompiled files should be verified to be up-to-date with their associated source files. Possible values are: \* `auto`: The effective value will be automatically determined by other build settings. \* `checked_hash`: Use the pyc file if the hash of the source file matches the hash recorded in the pyc file. This is most useful when working with code that you may modify. \* `unchecked_hash`: Always use the pyc file; don't check the pyc's hash against the source file. This is most useful when the code won't be modified. For more information on pyc invalidation modes, see https://docs.python.org/3/library/py_compile.html#py_compile.PycInvalidationMode | +| `precompile_optimize_level` | Integer; default is `0` The optimization level for precompiled files. For more information about optimization levels, see the `compile()` function's `optimize` arg docs at https://docs.python.org/3/library/functions.html#compile NOTE: The value `-1` means "current interpreter", which will be the interpreter used \_at build time when pycs are generated\_, not the interpreter used at runtime when the code actually runs. | +| `precompile_source_retention` | String; default is `"inherit"` Determines, when a source file is compiled, if the source file is kept in the resulting output or not. Valid values are: \* `inherit`: Inherit the value from the {flag}`--precompile_source_retention` flag. \* `keep_source`: Include the original Python source. \* `omit_source`: Don't include the original py source. | +| `pyc_collection` | String; default is `"inherit"` Determines whether pyc files from dependencies should be manually included. Valid values are: \* `inherit`: Inherit the value from {flag}`--precompile`. \* `include_pyc`: Add implicitly generated pyc files from dependencies. i.e. pyc files for targets that specify {attr}`precompile="inherit"`. \* `disabled`: Don't add implicitly generated pyc files. Note that pyc files may still come from dependencies that enable precompiling at the target level. | +| `python_version` | String; default is `"PY3"` Defunct, unused, does nothing. | +| `srcs_version` | String; default is `"PY2AND3"` Defunct, unused, does nothing. | +| `stamp` | Integer; default is `0` Whether to encode build information into the binary. Possible values: \* `stamp = 1`: Always stamp the build information into the binary, even in `--nostamp` builds. \*\*This setting should be avoided\*\*, since it potentially kills remote caching for the binary and any downstream actions that depend on it. \* `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` flag. Stamped binaries are not rebuilt unless their dependencies change. WARNING: Stamping can harm build performance by reducing cache hits and should be avoided if possible. | + +## py_runtime + +[View rule sourceopen_in_new](https://github.com/bazelbuild/rules_python/tree/0.40.0/python/private/py_runtime_rule.bzl) + +``` +py_runtime(name, abi_flags, bootstrap_template, compatible_with, coverage_tool, deprecation, distribs, exec_compatible_with, exec_properties, features, files, implementation_name, interpreter, interpreter_path, interpreter_version_info, pyc_tag, python_version, restricted_to, stage2_bootstrap_template, stub_shebang, tags, target_compatible_with, testonly, toolchains, visibility, zip_main_template) +``` + +Represents a Python runtime used to execute Python code. +A `py_runtime` target can represent either a \*platform runtime\* or an \*in-build +runtime\*. A platform runtime accesses a system-installed interpreter at a known +path, whereas an in-build runtime points to an executable target that acts as +the interpreter. In both cases, an "interpreter" means any executable binary or +wrapper script that is capable of running a Python script passed on the command +line, following the same conventions as the standard CPython interpreter. +A platform runtime is by its nature non-hermetic. It imposes a requirement on +the target platform to have an interpreter located at a specific path. An +in-build runtime may or may not be hermetic, depending on whether it points to +a checked-in interpreter or a wrapper script that accesses the system +interpreter. +Example +``` +load("@rules_python//python:py_runtime.bzl", "py_runtime") +py_runtime( +name = "python-2.7.12", +files = glob(["python-2.7.12/\*\*"]), +interpreter = "python-2.7.12/bin/python", +) +py_runtime( +name = "python-3.6.0", +interpreter_path = "/opt/pyenv/versions/3.6.0/bin/python", +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `abi_flags` | String; default is `""` The runtime's ABI flags, i.e. `sys.abiflags`. If not set, then it will be set based on flags. | +| `bootstrap_template` | [Label](/concepts/labels); default is `"@rules_python//python/private:bootstrap_template"` The bootstrap script template file to use. Should have %python_binary%, %workspace_name%, %main%, and %imports%. This template, after expansion, becomes the executable file used to start the process, so it is responsible for initial bootstrapping actions such as finding the Python interpreter, runfiles, and constructing an environment to run the intended Python application. While this attribute is currently optional, it will become required when the Python rules are moved out of Bazel itself. The exact variable names expanded is an unstable API and is subject to change. The API will become more stable when the Python rules are moved out of Bazel itself. See @bazel_tools//tools/python:python_bootstrap_template.txt for more variables. | +| `coverage_tool` | [Label](/concepts/labels); default is `None` This is a target to use for collecting code coverage information from {rule}`py_binary` and {rule}`py_test` targets. If set, the target must either produce a single file or be an executable target. The path to the single file, or the executable if the target is executable, determines the entry point for the python coverage tool. The target and its runfiles will be added to the runfiles when coverage is enabled. The entry point for the tool must be loadable by a Python interpreter (e.g. a `.py` or `.pyc` file). It must accept the command line arguments of [`coverage.py`](https://coverage.readthedocs.io), at least including the `run` and `lcov` subcommands. | +| `files` | List of [labels](/concepts/labels); default is `[]` For an in-build runtime, this is the set of files comprising this runtime. These files will be added to the runfiles of Python binaries that use this runtime. For a platform runtime this attribute must not be set. | +| `implementation_name` | String; default is `"cpython"` The Python implementation name (`sys.implementation.name`) | +| `interpreter` | [Label](/concepts/labels); default is `None` For an in-build runtime, this is the target to invoke as the interpreter. It can be either of: \* A single file, which will be the interpreter binary. It's assumed such interpreters are either self-contained single-file executables or any supporting files are specified in `files`. \* An executable target. The target's executable will be the interpreter binary. Any other default outputs (`target.files`) and plain files runfiles (`runfiles.files`) will be automatically included as if specified in the `files` attribute. NOTE: the runfiles of the target may not yet be properly respected/propagated to consumers of the toolchain/interpreter, see bazelbuild/rules_python/issues/1612 For a platform runtime (i.e. `interpreter_path` being set) this attribute must not be set. | +| `interpreter_path` | String; default is `""` For a platform runtime, this is the absolute path of a Python interpreter on the target platform. For an in-build runtime this attribute must not be set. | +| `interpreter_version_info` | Dictionary: String -> String; default is `{}` Version information about the interpreter this runtime provides. If not specified, uses {obj}`--python_version` The supported keys match the names for `sys.version_info`. While the input values are strings, most are converted to ints. The supported keys are: \* major: int, the major version number \* minor: int, the minor version number \* micro: optional int, the micro version number \* releaselevel: optional str, the release level \* serial: optional int, the serial number of the release :::{versionchanged} 0.36.0 {obj}`--python_version` determines the default value. ::: | +| `pyc_tag` | String; default is `""` Optional string; the tag portion of a pyc filename, e.g. the `cpython-39` infix of `foo.cpython-39.pyc`. See PEP 3147. If not specified, it will be computed from `implementation_name` and `interpreter_version_info`. If no pyc_tag is available, then only source-less pyc generation will function correctly. | +| `python_version` | String; default is `"PY3"` Whether this runtime is for Python major version 2 or 3. Valid values are `"PY2"` and `"PY3"`. The default value is controlled by the `--incompatible_py3_is_default` flag. However, in the future this attribute will be mandatory and have no default value. | +| `stage2_bootstrap_template` | [Label](/concepts/labels); default is `"@rules_python//python/private:stage2_bootstrap_template"` The template to use when two stage bootstrapping is enabled :::{seealso} {obj}`PyRuntimeInfo.stage2_bootstrap_template` and {obj}`--bootstrap_impl` ::: | +| `stub_shebang` | String; default is `"#!/usr/bin/env python3"` "Shebang" expression prepended to the bootstrapping Python stub script used when executing {rule}`py_binary` targets. See https://github.com/bazelbuild/bazel/issues/8685 for motivation. Does not apply to Windows. | +| `zip_main_template` | [Label](/concepts/labels); default is `"@rules_python//python/private:zip_main_template"` The template to use for a zip's top-level `\__main\_\_.py` file. This becomes the entry point executed when `python foo.zip` is run. :::{seealso} The {obj}`PyRuntimeInfo.zip_main_template` field. ::: | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/shell.mdx b/versions/8.6.0/reference/be/shell.mdx new file mode 100644 index 00000000..3dba5980 --- /dev/null +++ b/versions/8.6.0/reference/be/shell.mdx @@ -0,0 +1,130 @@ +--- +title: 'Shell Rules' +--- + +## Rules + +* [sh_binary](#sh_binary) +* [sh_library](#sh_library) +* [sh_test](#sh_test) + +## sh_binary + +[View rule sourceopen_in_new](https://github.com/bazelbuild/rules_shell/tree/v0.2.0/shell/private/sh_binary.bzl) + +``` +sh_binary(name, deps, srcs, data, args, compatible_with, deprecation, distribs, env, env_inherit, exec_compatible_with, exec_properties, features, output_licenses, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility) +``` + +The `sh_binary` rule is used to declare executable shell scripts. +(`sh_binary` is a misnomer: its outputs aren't necessarily binaries.) 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`); the rule name and the file name must be distinct. +`sh_binary` respects shebangs, so any available interpreter may be used (eg. +`#!/bin/zsh`) + +#### Example + +For a simple shell script with no dependencies and some data files: + +``` +sh_binary( + name = "foo", + srcs = ["foo.sh"], + data = glob(["datafiles/*.txt"]), +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of "library" targets to be aggregated into this target. See general comments about `deps` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical.deps). This attribute should be used to list other `sh_library` rules that provide interpreted program source code depended on by the code in `srcs`. The files provided by these rules will be present among the `runfiles` of this target. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of input files. This attribute should be used to list shell script source files that belong to this library. Scripts can load other scripts using the shell's `source` or `.` command. | +| `env_inherit` | List of strings; default is `[]` | + +## sh_library + +[View rule sourceopen_in_new](https://github.com/bazelbuild/rules_shell/tree/v0.2.0/shell/private/sh_library.bzl) + +``` +sh_library(name, deps, srcs, data, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, restricted_to, tags, target_compatible_with, testonly, toolchains, 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. + +You can use the [`filegroup`](/reference/be/general#filegroup) rule to aggregate data +files. + +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 +this rule has three attributes which are all essentially equivalent: +`srcs`, `deps` and `data`. +The current implementation does not distinguish between the elements of these lists. +All three attributes accept rules, source files and generated files. +It is however good practice to use the attributes for their usual purpose (as with other rules). + +#### Examples + +``` +sh_library( + name = "foo", + data = [ + ":foo_service_script", # an sh_binary with srcs + ":deploy_foo", # another sh_binary with srcs + ], +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of "library" targets to be aggregated into this target. See general comments about `deps` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical.deps). This attribute should be used to list other `sh_library` rules that provide interpreted program source code depended on by the code in `srcs`. The files provided by these rules will be present among the `runfiles` of this target. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of input files. This attribute should be used to list shell script source files that belong to this library. Scripts can load other scripts using the shell's `source` or `.` command. | + +## sh_test + +[View rule sourceopen_in_new](https://github.com/bazelbuild/rules_shell/tree/v0.2.0/shell/private/sh_test.bzl) + +``` +sh_test(name, deps, srcs, data, args, compatible_with, deprecation, distribs, env, env_inherit, exec_compatible_with, exec_properties, features, flaky, local, restricted_to, shard_count, size, tags, target_compatible_with, testonly, timeout, toolchains, visibility) +``` + +The `sh_binary` rule is used to declare executable shell scripts. +(`sh_binary` is a misnomer: its outputs aren't necessarily binaries.) 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`); the rule name and the file name must be distinct. +`sh_binary` respects shebangs, so any available interpreter may be used (eg. +`#!/bin/zsh`) + +#### Example + +For a simple shell script with no dependencies and some data files: + +``` +sh_binary( + name = "foo", + srcs = ["foo.sh"], + data = glob(["datafiles/*.txt"]), +) +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `deps` | List of [labels](/concepts/labels); default is `[]` The list of "library" targets to be aggregated into this target. See general comments about `deps` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical.deps). This attribute should be used to list other `sh_library` rules that provide interpreted program source code depended on by the code in `srcs`. The files provided by these rules will be present among the `runfiles` of this target. | +| `srcs` | List of [labels](/concepts/labels); default is `[]` The list of input files. This attribute should be used to list shell script source files that belong to this library. Scripts can load other scripts using the shell's `source` or `.` command. | \ No newline at end of file diff --git a/versions/8.6.0/reference/be/workspace.mdx b/versions/8.6.0/reference/be/workspace.mdx new file mode 100644 index 00000000..6fa7eec2 --- /dev/null +++ b/versions/8.6.0/reference/be/workspace.mdx @@ -0,0 +1,227 @@ +--- +title: 'Workspace Rules' +--- + +Workspace rules are used to pull in [external dependencies](/docs/external), typically +source code located outside the main repository. + +*Note:* besides the native workspace rules, Bazel also embeds various +[Starlark workspace rules](/rules/lib/repo/index), in particular those to deal +with git repositories or archives hosted on the web. + +## Rules + +* [bind](#bind) +* [local_repository](#local_repository) +* [new_local_repository](#new_local_repository) + +## bind + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/repository/BindRule.java) + +``` +bind(name, actual, compatible_with, deprecation, distribs, features, licenses, restricted_to, tags, target_compatible_with, testonly, visibility) +``` + +*Warning: use of `bind()` is not recommended. See "[Consider removing bind](https://github.com/bazelbuild/bazel/issues/1952)" for a long +discussion of its issues and alternatives. In particular, consider the use of +[`repo_mapping` +repository attributes](https://bazel.build/rules/repository_rules#attributes).* + +*Warning: `select()` cannot be used in `bind()`. See the [Configurable Attributes FAQ](/docs/configurable-attributes#bind-select) for +details.* + +Gives a target an alias in the `//external` package. + +The `//external` package is not a "normal" package: there is no external/ directory, +so it can be thought of as a "virtual package" that contains all bound targets. + +#### Examples + +To give a target an alias, `bind` it in the *WORKSPACE* file. For example, +suppose there is a `java_library` target called +`//third_party/javacc-v2`. This can be aliased by adding the following to the +*WORKSPACE* file: + +``` +bind( + name = "javacc-latest", + actual = "//third_party/javacc-v2", +) +``` + +Now targets can depend on `//external:javacc-latest` instead of +`//third_party/javacc-v2`. If javacc-v3 is released, the `bind` rule can be +updated and all of the BUILD files depending on `//external:javacc-latest` will now +depend on javacc-v3 without needing to be edited. + +Bind can also be used to make targets in external repositories available to your workspace. +For example, if there is a remote repository named `@my-ssl` imported in the +*WORKSPACE* file and it has a cc_library target `//src:openssl-lib`, you can +create an alias for this target using `bind`: + +``` +bind( + name = "openssl", + actual = "@my-ssl//src:openssl-lib", +) +``` + +Then, in a BUILD file in your workspace, the bound target can be used as follows: + +``` +cc_library( + name = "sign-in", + srcs = ["sign_in.cc"], + hdrs = ["sign_in.h"], + deps = ["//external:openssl"], +) +``` + +Within `sign_in.cc` and `sign_in.h`, the header files exposed by +`//external:openssl` can be referred to using their path relative to their repository +root. For example, if the rule definition for `@my-ssl//src:openssl-lib` looks like +this: + +``` +cc_library( + name = "openssl-lib", + srcs = ["openssl.cc"], + hdrs = ["openssl.h"], +) +``` + +Then `sign_in.cc`'s includes might look like this: + +``` +#include "sign_in.h" +#include "src/openssl.h" +``` + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `actual` | [Label](/concepts/labels); default is `None` The target to be aliased. This target must exist, but can be any type of rule (including bind). If this attribute is omitted, rules referring to this target in `//external` will simply not see this dependency edge. Note that this is different from omitting the `bind` rule completely: it is an error if an `//external` dependency does not have an associated `bind` rule. | + +## local_repository + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/repository/LocalRepositoryRule.java) + +``` +local_repository(name, path, repo_mapping) +``` + +Allows targets from a local directory to be bound. This means that the current repository can +use targets defined in this other directory. See the [bind +section](/reference/be/workspace#bind_examples) for more details. + +#### Examples + +Suppose the current repository is a chat client, rooted at the directory *~/chat-app*. It +would like to use an SSL library which is defined in a different repository: *~/ssl*. The +SSL library has a target `//src:openssl-lib`. + +The user can add a dependency on this target by adding the following lines to +*~/chat-app/WORKSPACE*: + +``` +local_repository( + name = "my-ssl", + path = "/home/user/ssl", +) +``` + +Targets would specify `@my-ssl//src:openssl-lib` as a dependency to depend on this +library. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `path` | String; required The path to the local repository's directory. This must be a path to the directory containing the repository's *WORKSPACE* file. The path can be either absolute or relative to the main repository's *WORKSPACE* file. | +| `repo_mapping` | Dictionary: String -> String; default is `{}` A dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository. For example, an entry `"@foo": "@bar"` declares that, for any time this repository depends on `"@foo"` (such as a dependency on `"@foo//some:target"`), it should actually resolve that dependency within globally-declared `"@bar"` (`"@bar//some:target"`). | + +## new_local_repository + +[View rule sourceopen_in_new](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/repository/NewLocalRepositoryRule.java) + +``` +new_local_repository(name, build_file, build_file_content, path, repo_mapping, workspace_file, workspace_file_content) +``` + +Allows a local directory to be turned into a Bazel repository. This means that the current +repository can define and use targets from anywhere on the filesystem. + +This rule creates a Bazel repository by creating a WORKSPACE file and subdirectory containing +symlinks to the BUILD file and path given. The build file should create targets relative to the +`path`. For directories that already contain a WORKSPACE file and a BUILD file, the +[`local_repository`](#local_repository) rule can be used. + +#### Examples + +Suppose the current repository is a chat client, rooted at the directory *~/chat-app*. It +would like to use an SSL library which is defined in a different directory: *~/ssl*. + +The user can add a dependency by creating a BUILD file for the SSL library +(~/chat-app/BUILD.my-ssl) containing: + +``` +java_library( + name = "openssl", + srcs = glob(['*.java']) + visibility = ["//visibility:public"], +) +``` + +Then they can add the following lines to *~/chat-app/WORKSPACE*: + +``` +new_local_repository( + name = "my-ssl", + path = "/home/user/ssl", + build_file = "BUILD.my-ssl", +) +``` + +This will create a `@my-ssl` repository that symlinks to */home/user/ssl*. +Targets can depend on this library by adding `@my-ssl//:openssl` to a target's +dependencies. + +You can also use `new_local_repository` to include single files, not just +directories. For example, suppose you had a jar file at /home/username/Downloads/piano.jar. You +could add just that file to your build by adding the following to your WORKSPACE file: + +``` +new_local_repository( + name = "piano", + path = "/home/username/Downloads/piano.jar", + build_file = "BUILD.piano", +) +``` + +And creating the following BUILD.piano file: + +``` +java_import( + name = "play-music", + jars = ["piano.jar"], + visibility = ["//visibility:public"], +) +``` + +Then targets can depend on `@piano//:play-music` to use piano.jar. + +### Arguments + +| Attributes | | +| --- | --- | +| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. | +| `build_file` | [Name](/concepts/labels#target-names); default is `None` A file to use as a BUILD file for this directory. Either build_file or build_file_content must be specified. This attribute is a label relative to the main workspace. The file does not need to be named BUILD, but can be. (Something like BUILD.new-repo-name may work well for distinguishing it from the repository's actual BUILD files.) | +| `build_file_content` | String; default is `""` The content for the BUILD file for this repository. Either build_file or build_file_content must be specified. | +| `path` | String; required A path on the local filesystem. This can be either absolute or relative to the main repository's WORKSPACE file. | +| `repo_mapping` | Dictionary: String -> String; default is `{}` A dictionary from local repository name to global repository name. This allows controls over workspace dependency resolution for dependencies of this repository. For example, an entry `"@foo": "@bar"` declares that, for any time this repository depends on `"@foo"` (such as a dependency on `"@foo//some:target"`), it should actually resolve that dependency within globally-declared `"@bar"` (`"@bar//some:target"`). | +| `workspace_file` | [Name](/concepts/labels#target-names); default is `None` The file to use as the WORKSPACE file for this repository. Either workspace_file or workspace_file_content can be specified, but not both. This attribute is a label relative to the main workspace. The file does not need to be named WORKSPACE, but can be. (Something like WORKSPACE.new-repo-name may work well for distinguishing it from the repository's actual WORKSPACE files.) | +| `workspace_file_content` | String; default is `""` The content for the WORKSPACE file for this repository. Either workspace_file or workspace_file_content can be specified, but not both. | \ No newline at end of file diff --git a/versions/8.6.0/reference/command-line-reference.mdx b/versions/8.6.0/reference/command-line-reference.mdx new file mode 100644 index 00000000..56fcf673 --- /dev/null +++ b/versions/8.6.0/reference/command-line-reference.mdx @@ -0,0 +1,12410 @@ +--- +title: 'Command-Line Reference' +--- + +``` +bazel [] [] +``` + +or + +``` +bazel [] [] -- [] +``` + +See the [User's Guide](/docs/build#specifying-build-targets) for the +target patterns syntax. + +## Option Syntax + +Options can be passed to Bazel in different ways. Options that require a value +can be passed with either an equals sign or a space: + +``` +--