Back to Bazel

Functions

docs/versions/6.0.0/reference/be/functions.mdx

9.1.026.2 KB
Original Source
<html devsite> <head> <meta name="project_path" value="/_project.yaml"> <meta name="book_path" value="/versions/6.0.0/_book.yaml"> </head> <body> <!-- This document is synchronized with Bazel releases. To edit, submit changes to the Bazel source code. --> <!-- Generated by //src/main/java/com/google/devtools/build/docgen:build-encyclopedia.zip --> <h1 class="page-title">Functions</h1> <h2>Contents</h2> <ul> <li><a href="#package">package</a></li> <li><a href="#package_group">package_group</a></li> <li><a href="#exports_files">exports_files</a></li> <li><a href="#glob">glob</a></li> <li><a href="#select">select</a></li> <li><a href="#subpackages">subpackages</a></li> </ul> <!-- ================================================================= package() ================================================================= --> <h2 id="package">package</h2> <pre> package(default_deprecation, default_testonly, default_visibility, features) </pre> <p>This function declares metadata that applies to every subsequent rule in the package. It is used at most once within a package (BUILD file).</p> <p>The package() function should be called right after all the load() statements at the top of the file, before any rule.</p> <h3 id="package_args">Arguments</h3> <table class="table table-condensed table-bordered table-params"> <colgroup> <col class="col-param" /> <col class="param-description" /> </colgroup> <thead> <tr> <th>Attribute</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td id="package.default_visibility"><code>default_visibility</code></td> <td> <p><code>List of <a href="/versions/6.0.0/concepts/labels">labels</a>; optional</code></p> <p>The default visibility of the rules in this package.</p> <p>Every rule in this package has the visibility specified in this attribute, unless otherwise specified in the <code>visibility</code> attribute of the rule. For detailed information about the syntax of this attribute, see the documentation of <a href="/versions/6.0.0/concepts/visibility">visibility</a>. The package default visibility does not apply to <a href="#exports_files">exports_files</a>, which is public by default.</p> </td> </tr> <tr> <td id="package.default_deprecation"><code>default_deprecation</code></td> <td> <p><code>String; optional</code></p> <p>Sets the default <a href="common-definitions.html#common.deprecation"> <code>deprecation</code></a> message for all rules in this package.</p> </td> </tr> <tr> <td id="package.default_testonly"><code>default_testonly</code></td> <td> <p><code>Boolean; optional; default is False except as noted</code></p> <p>Sets the default <a href="common-definitions.html#common.testonly"> <code>testonly</code></a> property for all rules in this package.</p> <p>In packages under <code>javatests</code> the default value is 1.</p> </td> </tr> <tr> <td id="package.features"><code>features</code></td> <td> <p><code>List strings; optional</code></p> <p>Sets various flags that affect the semantics of this BUILD file.</p> <p>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.</p>
  </td>
</tr>
</tbody> </table> <h3 id="package_example">Examples</h3>

The declaration below declares that the rules in this package are visible only to members of package group <code>//foo:target</code>. Individual visibility declarations on a rule, if present, override this specification.

<pre class="code"> package(default_visibility = ["//foo:target"]) </pre> <!-- ================================================================= package_group() ================================================================= --> <h2 id="package_group">package_group</h2> <pre>package_group(name, packages, includes)</pre> <p>This function defines a set of <a href="/versions/6.0.0/concepts/build-ref#packages">packages</a> and associates a label with the set. The label can be referenced in <code>visibility</code> attributes.</p> <p>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 <a href="common-definitions.html#common.visibility">visibility</a> attribute.</p> <p>A given package is considered to be in the group if it either matches the <code>packages</code> attribute, or is already contained in one of the other package groups mentioned in the <code>includes</code> attribute.</p> <p>Package groups are technically targets, but are not created by rules, and do not themselves have any visibility protection.</p> <h3 id="package_group_args">Arguments</h3> <table class="table table-condensed table-bordered table-params"> <colgroup> <col class="col-param" /> <col class="param-description" /> </colgroup> <thead> <tr> <th>Attribute</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td id="package_group.name"><code>name</code></td> <td> <p><code><a href="/versions/6.0.0/concepts/labels#target-names">Name</a>; required</code></p> <p>A unique name for this target.</p> </td> </tr> <tr> <td id="package_group.packages"><code>packages</code></td> <td> <p><code>List of strings; optional</code></p> <p>A list of zero or more package specifications.</p>
    <p>Each package specification string can have one of the following
    forms:</p>

    <ol>

    <li>The full name of a package, without its repository, starting with a
    double slash. For example, <code>//foo/bar</code> specifies the package
    having that name and which lives in the same repository as the package
    group.

    <li>As above, but with a trailing <code>/...</code>. For example, <code>
    //foo/...</code> specifies the set of <code>//foo</code> and all its
    subpackages. <code>//...</code> specifies all packages in the current
    repository.

    <li>The strings <code>public</code> or <code>private</code>, which
    respectively specify every package or no package. (This form requires
    the flag <code>--incompatible_package_group_has_public_syntax</code> to
    be set.)

    </ol>

    <p>In addition, the first two kinds of package specifications may also
    be prefixed with <code>-</code> to indicate that they are negated.</p>

    <p>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 <code>[//foo/..., -//foo/tests/...]</code>
    includes all subpackages of <code>//foo</code> that are not also
    subpackages of <code>//foo/tests</code>. (<code>//foo</code> itself is
    included while </code>//foo/tests</code> itself is not.)</p>

    <p>Aside from public visibility, there is no way to directly specify
    packages outside the current repository.</p>

    <p>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 <code>private</code>.

    <p><i>Note:</i> Prior to Bazel 6.0, the specification <code>//...</code>
    had a legacy behavior of being the same as <code>public</code>. This
    behavior is fixed when
    <code>--incompatible_fix_package_group_reporoot_syntax</code> is
    enabled, which is the default after Bazel 6.0.</p>

    <p><i>Note:</i> Prior to Bazel 6.0, when this attribute is serialized as
    part of <code>bazel query --output=proto</code> (or
    <code>--output=xml</code>), the leading slashes are omitted. For
    instance, <code>//pkg/foo/...</code> will output as
    <code>\"pkg/foo/...\"</code>. This behavior is fixed when
    <code>--incompatible_package_group_includes_double_slash</code> is
    enabled, which is the default after Bazel 6.0.</p>
  </td>
</tr>
<tr>
  <td id="package_group.includes"><code>includes</code></td>
  <td>
    <p><code>List of <a href="/versions/6.0.0/concepts/labels">labels</a>; optional</code></p>
    <p>Other package groups that are included in this one.</p>

    <p>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
    <code>a</code> includes package group <code>b</code>, and <code>b</code>
    includes package group <code>c</code>, then every package in
    <code>c</code> will also be a member of <code>a</code>.</p>

    <p>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.</p>
  </td>
</tr>
</tbody> </table> <h3 id="package_group_example">Examples</h3> <p>The following <code>package_group</code> declaration specifies a package group called "tropical" that contains tropical fruits.</p> <pre class="code"> package_group( name = "tropical", packages = [ "//fruits/mango", "//fruits/orange", "//fruits/papaya/...", ], ) </pre> <p>The following declarations specify the package groups of a fictional application:</p> <pre class="code"> 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"], ) </pre> <!-- ================================================================= exports_files([label, ...]) ================================================================= --> <h2 id="exports_files">exports_files</h2> <pre>exports_files([<i>label</i>, ...], visibility, licenses)</pre> <p> <code>exports_files()</code> specifies a list of files belonging to this package that are exported to other packages. </p> <p> The BUILD file for a package may only refer directly to source files belonging to another package if they are explicitly exported with an <code>exports_files()</code> statement. Read more about <a href="/versions/6.0.0/concepts/visibility#visibility-of-a-file">visibility of files</a>. </p> <p> As a legacy behaviour, also files mentioned as input to a rule are exported with the default visibility until the flag <a href="https://github.com/bazelbuild/bazel/issues/10225"><code>--incompatible_no_implicit_file_export</code></a> is flipped. However, this behavior should not be relied upon and actively migrated away from. </p> <h3 id="exports_files_args">Arguments</h3> <p> 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 <code><a href="functions.html#package">package</a></code> function. The <a href="common-definitions.html#common.licenses">licenses</a> can also be specified. </p> <h3 id="exports_files_example">Example</h3> <p> The following example exports <code>golden.txt</code>, a text file from the <code>test_data</code> package, so that other packages may use it, for example, in the <code>data</code> attribute of tests. </p> <pre class="code"> # from //test_data/BUILD exports_files(["golden.txt"]) </pre> <!-- ================================================================= glob() ================================================================= --> <h2 id="glob">glob</h2> <pre>glob(include, exclude=[], exclude_directories=1, allow_empty=True)</pre> <p> 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). </p> <p> A source file's Label is included in the result if the file's package-relative path matches any of the <code>include</code> patterns and none of the <code>exclude</code> patterns. </p> <p> The <code>include</code> and <code>exclude</code> 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 <code>/</code>. Segments may contain the <code>*</code> wildcard: this matches any substring in the path segment (even the empty substring), excluding the directory separator <code>/</code>. This wildcard can be used multiple times within one path segment. Additionally, the <code>**</code> wildcard can match zero or more complete path segments, but it must be declared as a standalone path segment. </p>

Examples:

<ul> <li><code>foo/bar.txt</code> matches exactly the <code>foo/bar.txt</code> file in this package</li> <li><code>foo/*.txt</code> matches every file in the <code>foo/</code> directory if the file ends with <code>.txt</code> (unless <code>foo/</code> is a subpackage)</li> <li><code>foo/a*.htm*</code> matches every file in the <code>foo/</code> directory that starts with <code>a</code>, then has an arbitrary string (could be empty), then has <code>.htm</code>, and ends with another arbitrary string; such as <code>foo/axx.htm</code> and <code>foo/a.html</code> or <code>foo/axxx.html</code></li> <li><code>**/a.txt</code> matches every <code>a.txt</code> file in every subdirectory of this package</li> <li><code>**/bar/**/*.txt</code> matches every <code>.txt</code> file in every subdirectory of this package, if at least one directory on the resulting path is called <code>bar</code>, such as <code>xxx/bar/yyy/zzz/a.txt</code> or <code>bar/a.txt</code> (remember that <code>**</code> also matches zero segments) or <code>bar/zzz/a.txt</code></li> <li><code>**</code> matches every file in every subdirectory of this package</li> <li><code>foo**/a.txt</code> is an invalid pattern, because <code>**</code> must stand on its own as a segment</li> </ul> <p> If the <code>exclude_directories</code> argument is enabled (set to 1), files of type directory will be omitted from the results (default 1). </p> <p> If the <code>allow_empty</code> argument is set to <code>False</code>, the <code>glob</code> function will error-out if the result would otherwise be the empty list. </p> <p> There are several important limitations and caveats: </p> <ol> <li> <p> Since <code>glob()</code> runs during BUILD file evaluation, <code>glob()</code> 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 <a href="#glob_example">example</a> below with <code>:mylib</code> and <code>:gen_java_srcs</code>. </p> </li> <li> <p> If a rule has the same name as a matched source file, the rule will "shadow" the file. </p> <p> To understand this, remember that <code>glob()</code> returns a list of paths, so using <code>glob()</code> in other rules' attribute (e.g. <code>srcs = glob(["*.cc"])</code>) has the same effect as listing the matched paths explicitly. If for example <code>glob()</code> yields <code>["Foo.java", "bar/Baz.java"]</code> 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 <code>glob()</code> will use the "Foo.java" rule (its outputs) instead of the "Foo.java" file. See <a href="https://github.com/bazelbuild/bazel/issues/10395#issuecomment-583714657">GitHub issue #10395</a> for more details. </p> </li> <li> Globs may match files in subdirectories. And subdirectory names may be wildcarded. However... </li> <li> <p> Labels are not allowed to cross the package boundary and glob does not match files in subpackages. </p>
<p>
For example, the glob expression <code>**/*.cc</code> in package
<code>x</code> does not include <code>x/y/z.cc</code> if
<code>x/y</code> exists as a package (either as
<code>x/y/BUILD</code>, or somewhere else on the package-path). This
means that the result of the glob expression actually depends on the
existence of BUILD files &mdash; that is, the same glob expression would
include <code>x/y/z.cc</code> if there was no package called
<code>x/y</code> or it was marked as deleted using the
<a href="/versions/6.0.0/docs/user-manual#flag--deleted_packages">--deleted_packages</a>
flag.
</p>
</li> <li> The restriction above applies to all glob expressions, no matter which wildcards they use. </li> <li> A hidden file with filename starting with <code>.</code> is completely matched by both the <code>**</code> and the <code>*</code> wildcards. If you want to match a hidden file with a compound pattern, your pattern needs to begin with a <code>.</code>. For example, <code>*</code> and <code>.*.txt</code> will match <code>.foo.txt</code>, but <code>*.txt</code> 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.
</li> <li> The "**" wildcard has one corner case: the pattern <code>"**"</code> doesn't match the package's directory path. That is to say, <code>glob(["**"], exclude_directories = 0)</code> 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). </li> </ol> <p> In general, you should <b>try to provide an appropriate extension (e.g. *.html) instead of using a bare '*'</b> 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. </p> <p> When writing build rules you can enumerate the elements of the glob. This enables generating individual rules for every input, for example. See the <a href="#expanded_glob_example">expanded glob example</a> section below. </p> <h3 id="glob_example">Glob Examples</h3> <p> Create a Java library built from all java files in this directory, and all files generated by the <code>:gen_java_srcs</code> rule.</p> <pre class="code"> java_library( name = "mylib", srcs = glob(["*.java"]) + [":gen_java_srcs"], deps = "...", )

genrule( name = "gen_java_srcs", outs = [ "Foo.java", "Bar.java", ], ... ) </pre>

<p>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 (**).</p> <pre class="code"> sh_test( name = "mytest", srcs = ["mytest.sh"], data = glob( ["testdata/*.txt"], exclude = ["testdata/experimental.txt"], ), ) </pre> <h3 id="recursive_glob_example">Recursive Glob Examples</h3> <p>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.)</p> <pre class="code"> sh_test( name = "mytest", srcs = ["mytest.sh"], data = glob(["testdata/**/*.txt"]), ) </pre> <p>Create a library built from all java files in this directory and all subdirectories except those whose path includes a directory named testing. <b>This pattern should be avoided if possible, as it can reduce build incrementality and therefore increase build times.</b> </p> <pre class="code"> java_library( name = "mylib", srcs = glob( ["**/*.java"], exclude = ["**/testing/**"], ), ) </pre> <h3 id="expanded_glob_example">Expanded Glob Examples</h3> <p> Create an individual genrule for *_test.cc in the current directory that counts the number of lines in the file. </p> <pre class="code"> # 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 $&lt; &gt;$@", ) for f in glob(["*_test.cc"])] </pre> <p> 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 <code>bazel query '//foo:all'</code> will list all rules that were generated: <pre> $ bazel query '//foo:all' | sort //foo:count_lines_a_test //foo:count_lines_b_test //foo:count_lines_c_test </pre> <!-- ================================================================= select() ================================================================= --> <h2 id="select">select</h2> <pre> select( {conditionA: valuesA, conditionB: valuesB, ...}, no_match_error = "custom message" ) </pre> <p><code>select()</code> is the helper function that makes a rule attribute <a href="common-definitions.html#configurable-attributes">configurable</a>. It can replace the right-hand side of

<i>almost</i> 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.

</p> <p>Basic use is as follows:</p> <pre class="code"> sh_binary( name = "mytarget", srcs = select({ ":conditionA": ["mytarget_a.sh"], ":conditionB": ["mytarget_b.sh"], "//conditions:default": ["mytarget_default.sh"] }) ) </pre> <p>This makes the <code>srcs</code> attribute of a <code>sh_binary</code> configurable by replacing its normal label list assignment with a <code>select</code> call that maps configuration conditions to matching values. Each condition is a label reference to a <code><a href="general.html#config_setting">config_setting</a></code> or <code><a href="platform.html#constraint_value">constraint_value</a></code>, which "matches" if the target's configuration matches an expected set of values. The value of <code>mytarget#srcs</code> then becomes whichever label list matches the current invocation. </p> <p>Notes:</p> <ul> <li>Exactly one condition is selected on any invocation. </li> <li>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. </li> <li>If multiple conditions match and one is not a specialization of all the others, Bazel fails with an error. </li> <li>The special pseudo-label <code>//conditions:default</code> is considered to match if no other condition matches. If this condition is left out, some other rule must match to avoid an error. </li> <li><code>select</code> can be embedded <i>inside</i> a larger attribute assignment. So <code>srcs = ["common.sh"] + select({ ":conditionA": ["myrule_a.sh"], ...})</code> and <code> srcs = select({ ":conditionA": ["a.sh"]}) + select({ ":conditionB": ["b.sh"]})</code> are valid expressions. </li> <li><code>select</code> works with most, but not all, attributes. Incompatible attributes are marked <code>nonconfigurable</code> in their documentation. <!-- ================================================================= subpackages() ================================================================= --> <h2 id="subpackages">subpackages</h2> <pre>subpackages(include, exclude=[], allow_empty=True)</pre> <p> <code>subpackages()</code> is a helper function, similar to <code>glob()</code> that lists subpackages instead of files and directories. It uses the same path patterns as <code>glob()</code> and can match any subpackage that is a direct descendant of the currently loading BUILD file. See <a href="#glob">glob</a> for a detailed explanation and examples of include and exclude patterns. </p> <p> 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 <code>include</code> and not those in <code>exclude</code>. <h3 id=subpackages_example">Example</h3> <p> The following example lists all the direct subpackages for the package <code>foo/BUILD</code> <pre class="code"> # The following BUILD files exist: # foo/BUILD # foo/bar/baz/BUILD # foo/sub/BUILD # foo/sub/deeper/BUILD # # In foo/BUILD a call to subs = subpackages(include = ["**"]) # results in subs == ["sub", "bar/baz"] # # 'sub/deeper' is not included because it is a subpackage of 'foo/sub' not of # 'foo' </pre>
<p>
In general it is preferred that instead of calling this function directly
that users use the 'subpackages' module of
<a href="https://github.com/bazelbuild/bazel-skylib">skylib</a>.
<!-- Generated footer --> </body> </html>