Back to Bazel

General

docs/versions/6.2.0/reference/be/general.mdx

9.1.157.3 KB
Original Source
<html devsite> <head> <meta name="project_path" value="/_project.yaml"> <meta name="book_path" value="/versions/6.2.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 --> <html> <body> <h1 class="page-title">General Rules</h1> <h2>Rules</h2> <ul> <li> <a href="#alias"> alias </a> </li> <li> <a href="#config_setting"> config_setting </a> </li> <li> <a href="#filegroup"> filegroup </a> </li> <li> <a href="#genquery"> genquery </a> </li> <li> <a href="#genrule"> genrule </a> </li> <li> <a href="#test_suite"> test_suite </a> </li> </ul> <h2 id="alias"> alias </h2> <pre class="rule-signature">alias(<a href="#alias.name">name</a>, <a href="#alias.actual">actual</a>, <a href="common-definitions.html#common.compatible_with">compatible_with</a>, <a href="common-definitions.html#common.deprecation">deprecation</a>, <a href="common-definitions.html#common.features">features</a>, <a href="common-definitions.html#common.restricted_to">restricted_to</a>, <a href="common-definitions.html#common.tags">tags</a>, <a href="common-definitions.html#common.target_compatible_with">target_compatible_with</a>, <a href="common-definitions.html#common.testonly">testonly</a>, <a href="common-definitions.html#common.visibility">visibility</a>)</pre> <p> The <code>alias</code> rule creates another name a rule can be referred to as. </p> <p> Aliasing only works for "regular" targets. In particular, <code>package_group</code> and <code>test_suite</code> cannot be aliased. </p> <p> The alias rule has its own visibility declaration. In all other respects, it behaves like the rule it references (e.g. testonly <em>on the alias</em> is ignored; the testonly-ness of the referenced rule is used instead) with some minor exceptions: <ul> <li> Tests are not run if their alias is mentioned on the command line. To define an alias that runs the referenced test, use a <a href="#test_suite"><code>test_suite</code></a> rule with a single target in its <a href="#test_suite.tests"><code>tests</code></a> attribute. </li> <li> When defining environment groups, the aliases to <code>environment</code> rules are not supported. They are not supported in the <code>--target_environment</code> command line option, either. </li> </ul> </p> <h4 id="alias_example">Examples</h4> <pre class="code"> filegroup( name = "data", srcs = ["data.txt"], ) alias( name = "other", actual = ":data", ) </pre> <h3 id="alias_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 colspan="2">Attributes</th> </tr> </thead> <tbody> <tr> <td id="alias.name"><code>name</code></td> <td> <p><code><a href="/versions/6.2.0/concepts/labels#target-names">Name</a>; required</code></p> <p>A unique name for this target.</p>
    </td>
  </tr>
            <tr>
    <td id="alias.actual">
      <code>actual</code>
    </td>
    <td>
                <p><code><a href="/versions/6.2.0/concepts/labels">Label</a>; required</code></p>
                          The target this alias refers to. It does not need to be a rule, it can also be an input
      file.

    </td>
  </tr>
                                                                                          </tbody>
</table> <h2 id="config_setting"> config_setting </h2> <pre class="rule-signature">config_setting(<a href="#config_setting.name">name</a>, <a href="#config_setting.constraint_values">constraint_values</a>, <a href="#config_setting.define_values">define_values</a>, <a href="common-definitions.html#common.deprecation">deprecation</a>, <a href="common-definitions.html#common.distribs">distribs</a>, <a href="common-definitions.html#common.features">features</a>, <a href="#config_setting.flag_values">flag_values</a>, <a href="common-definitions.html#typical.licenses">licenses</a>, <a href="common-definitions.html#common.tags">tags</a>, <a href="common-definitions.html#common.testonly">testonly</a>, <a href="#config_setting.values">values</a>, <a href="common-definitions.html#common.visibility">visibility</a>)</pre> <p> Matches an expected configuration state (expressed as build flags or platform constraints) for the purpose of triggering configurable attributes. See <a href="/versions/6.2.0/reference/be/functions.html#select">select</a> for how to consume this rule and <a href="/versions/6.2.0/reference/be/common-definitions#configurable-attributes"> Configurable attributes</a> for an overview of the general feature. <h4 id="config_setting_examples">Examples</h4> <p>The following matches any build that sets <code>--compilation_mode=opt</code> or <code>-c opt</code> (either explicitly at the command line or implicitly from .bazelrc files): </p> <pre class="code"> config_setting( name = "simple", values = {"compilation_mode": "opt"} ) </pre> <p>The following matches any build that targets ARM and applies the custom define <code>FOO=bar</code> (for instance, <code>bazel build --cpu=arm --define FOO=bar ...</code>): </p> <pre class="code"> config_setting( name = "two_conditions", values = { "cpu": "arm", "define": "FOO=bar" } ) </pre> <p>The following matches any build that sets <a href="https://bazel.build/versions/6.2.0/rules/config#user-defined-build-settings">user-defined flag</a> <code>--//custom_flags:foo=1</code> (either explicitly at the command line or implicitly from .bazelrc files): </p> <pre class="code"> config_setting( name = "my_custom_flag_is_set", flag_values = { "//custom_flags:foo": "1" }, ) </pre> <p>The following matches any build that targets a platform with an x86_64 architecture and glibc version 2.25, assuming the existence of a <code>constraint_value</code> with label <code>//example:glibc_2_25</code>. Note that a platform still matches if it defines additional constraint values beyond these two. </p> <pre class="code"> config_setting( name = "64bit_glibc_2_25", constraint_values = [ "@platforms//cpu:x86_64", "//example:glibc_2_25", ] ) </pre>

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 <code>config_setting</code> doesn't match the top-level command-line flags, it may still match some build targets.

<h4 id="config_setting_notes">Notes</h4> <ul> <li>See <a href="/versions/6.2.0/reference/be/functions.html#select">select</a> for what happens when multiple <code>config_setting</code>s match the current configuration state. </li>
<li>For flags that support shorthand forms (e.g. <code>--compilation_mode</code> vs.
  <code>-c</code>), <code>values</code> definitions must use the full form. These automatically
  match invocations using either form.
</li>

<li>
  If a flag takes multiple values (like <code>--copt=-Da --copt=-Db</code> or a list-typed
  <a href="https://bazel.build/versions/6.2.0/rules/config#user-defined-build-settings">
  Starlark flag</a>), <code>values = { "flag": "a" }</code> matches if <code>"a"</code> is
  present <i>anywhere</i> in the actual list.

  <p>
    <code>values = { "myflag": "a,b" }</code> works the same way: this matches
    <code>--myflag=a --myflag=b</code>, <code>--myflag=a --myflag=b --myflag=c</code>,
    <code>--myflag=a,b</code>, and <code>--myflag=c,b,a</code>. Exact semantics vary between
    flags. For example, <code>--copt</code> doesn't support multiple values <i>in the same
    instance</i>: <code>--copt=a,b</code> produces <code>["a,b"]</code> while <code>--copt=a
    --copt=b</code> produces <code>["a", "b"]</code> (so <code>values = { "copt": "a,b" }</code>
    matches the former but not the latter). But <code>--ios_multi_cpus</code> (for Apple rules)
    <i>does</i>: <code>-ios_multi_cpus=a,b</code> and <code>ios_multi_cpus=a --ios_multi_cpus=b
    </code> both produce <code>["a", "b"]</code>. Check flag definitions and test your
    conditions carefully to verify exact expectations.
  </p>
</li>

<li>If you need to define conditions that aren't modeled by built-in build flags, use
  <a href="https://bazel.build/versions/6.2.0/rules/config#user-defined-build-settings">
  Starlark-defined flags</a>. You can also use <code>--define</code>, but this offers weaker
  support and is not recommended. See
  <a href="/versions/6.2.0/reference/be/common-definitions#configurable-attributes">here</a> for more discussion.
</li>

<li>Avoid repeating identical <code>config_setting</code> definitions in different packages.
  Instead, reference a common <code>config_setting</code> that defined in a canonical package.
</li>

<li><a href="general.html#config_setting.values"><code>values</code></a>,
   <a href="general.html#config_setting.define_values"><code>define_values</code></a>, and
   <a href="general.html#config_setting.constraint_values"><code>constraint_values</code></a>
   can be used in any combination in the same <code>config_setting</code> but at least one must
   be set for any given <code>config_setting</code>.
</li>
</ul> <h3 id="config_setting_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 colspan="2">Attributes</th> </tr> </thead> <tbody> <tr> <td id="config_setting.name"><code>name</code></td> <td> <p><code><a href="/versions/6.2.0/concepts/labels#target-names">Name</a>; required</code></p> <p>A unique name for this target.</p>
    </td>
  </tr>
            <tr>
    <td id="config_setting.constraint_values">
      <code>constraint_values</code>
    </td>
    <td>
                <p><code>List of <a href="/versions/6.2.0/concepts/labels">labels</a>; optional; <a href="common-definitions.html#configurable-attributes">nonconfigurable</a></code></p>
                          The minimum set of <code>constraint_values</code> that the target platform must specify
      in order to match this <code>config_setting</code>. (The execution platform is not
      considered here.) Any additional constraint values that the platform has are ignored. See
      <a href="https://bazel.build/versions/6.2.0/docs/configurable-attributes#platforms">
      Configurable Build Attributes</a> for details.

      <p>In the case where two <code>config_setting</code>s both match in the same
      <code>select</code>, this attribute is not considered for the purpose of determining
      whether one of the <code>config_setting</code>s is a specialization of the other. In other
      words, one <code>config_setting</code> cannot match a platform more strongly than another.

    </td>
  </tr>
                  <tr>
    <td id="config_setting.define_values">
      <code>define_values</code>
    </td>
    <td>
                <p><code>Dictionary: String -> String; optional; <a href="common-definitions.html#configurable-attributes">nonconfigurable</a></code></p>
                          The same as <a href="/versions/6.2.0/reference/be/general.html#config_setting.values"><code>values</code></a> but
      specifically for the <code>--define</code> flag.

      <p><code>--define</code> is special because its syntax (<code>--define KEY=VAL</code>)
        means <code>KEY=VAL</code> is a <i>value</i> from a Bazel flag perspective.
      </p>

      <p>That means:

      <pre class="code">
        config_setting(
            name = "a_and_b",
            values = {
                "define": "a=1",
                "define": "b=2",
            })
      </pre>

      <p>doesn't work because the same key (<code>define</code>) appears twice in the
      dictionary. This attribute solves that problem:

      <pre class="code">
        config_setting(
            name = "a_and_b",
            define_values = {
                "a": "1",
                "b": "2",
            })
      </pre>

      <p>correctly matches <code>bazel build //foo --define a=1 --define b=2</code>.

      <p><code>--define</code> can still appear in
      <a href="/versions/6.2.0/reference/be/general.html#config_setting.values"><code>values</code></a> with normal flag syntax,
      and can be mixed freely with this attribute as long as dictionary keys remain distinct.

    </td>
  </tr>
                                                <tr>
    <td id="config_setting.flag_values">
      <code>flag_values</code>
    </td>
    <td>
                <p><code>Dictionary: <a href="/versions/6.2.0/concepts/labels">label</a> -> String; optional; <a href="common-definitions.html#configurable-attributes">nonconfigurable</a></code></p>
                          The same as <a href="/versions/6.2.0/reference/be/general.html#config_setting.values"><code>values</code></a> but
      for <a href="https://bazel.build/versions/6.2.0/rules/config#user-defined-build-settings">
      user-defined build flags</a>.

      <p>This is a distinct attribute because user-defined flags are referenced as labels while
      built-in flags are referenced as arbitrary strings.


    </td>
  </tr>
                                                <tr>
    <td id="config_setting.values">
      <code>values</code>
    </td>
    <td>
                <p><code>Dictionary: String -> String; optional; <a href="common-definitions.html#configurable-attributes">nonconfigurable</a></code></p>
                          The set of configuration values that match this rule (expressed as build flags)

      <p>This rule inherits the configuration of the configured target that
        references it in a <code>select</code> 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
        <code>values = {"compilation_mode": "opt"}</code> matches the invocations
        <code>bazel build --compilation_mode=opt ...</code> and
        <code>bazel build -c opt ...</code> on target-configured rules.
      </p>

      <p>For convenience's sake, configuration values are specified as build flags (without
        the preceding <code>"--"</code>). 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, a host configuration's "cpu" matches the value of
        <code>--host_cpu</code>, not <code>--cpu</code>. So different instances of the
        same <code>config_setting</code> may match the same invocation differently
        depending on the configuration of the rule using them.
      </p>

      <p>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.
         <code>bazel build --copt=foo --copt=bar --copt=baz ...</code>), a match occurs if
         <i>any</i> of those settings match.
      <p>

    </td>
  </tr>
                    </tbody>
</table> <h2 id="filegroup"> filegroup </h2> <pre class="rule-signature">filegroup(<a href="#filegroup.name">name</a>, <a href="#filegroup.srcs">srcs</a>, <a href="#filegroup.data">data</a>, <a href="common-definitions.html#common.compatible_with">compatible_with</a>, <a href="common-definitions.html#common.deprecation">deprecation</a>, <a href="common-definitions.html#common.distribs">distribs</a>, <a href="common-definitions.html#common.features">features</a>, <a href="common-definitions.html#typical.licenses">licenses</a>, <a href="#filegroup.output_group">output_group</a>, <a href="common-definitions.html#common.restricted_to">restricted_to</a>, <a href="common-definitions.html#common.tags">tags</a>, <a href="common-definitions.html#common.target_compatible_with">target_compatible_with</a>, <a href="common-definitions.html#common.testonly">testonly</a>, <a href="common-definitions.html#common.visibility">visibility</a>)</pre> <p> Use <code>filegroup</code> to give a convenient name to a collection of targets. These can then be referenced from other rules. </p> <p> Using <code>filegroup</code> is encouraged instead of referencing directories directly. The latter is unsound since 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 <a href="/versions/6.2.0/reference/be/functions.html#glob">glob</a>, <code>filegroup</code> can ensure that all files are explicitly known to the build system. </p> <h4 id="filegroup_example">Examples</h4> <p> To create a <code>filegroup</code> consisting of two source files, do </p> <pre class="code"> filegroup( name = "mygroup", srcs = [ "a_file.txt", "some/subdirectory/another_file.txt", ], ) </pre> <p> Or, use a <code>glob</code> to grovel a testdata directory: </p> <pre class="code"> filegroup( name = "exported_testdata", srcs = glob([ "testdata/*.dat", "testdata/logs/**&#47;*.log", ]), ) </pre> <p> To make use of these definitions, reference the <code>filegroup</code> with a label from any rule: </p> <pre class="code"> cc_library( name = "my_library", srcs = ["foo.cc"], data = [ "//my_package:exported_testdata", "//my_package:mygroup", ], ) </pre> <h3 id="filegroup_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 colspan="2">Attributes</th> </tr> </thead> <tbody> <tr> <td id="filegroup.name"><code>name</code></td> <td> <p><code><a href="/versions/6.2.0/concepts/labels#target-names">Name</a>; required</code></p> <p>A unique name for this target.</p>
    </td>
  </tr>
            <tr>
    <td id="filegroup.srcs">
      <code>srcs</code>
    </td>
    <td>
                <p><code>List of <a href="/versions/6.2.0/concepts/labels">labels</a>; optional</code></p>
                        The list of targets that are members of the file group.
    <p>
      It is common to use the result of a <a href="/versions/6.2.0/reference/be/functions.html#glob">glob</a> expression for
      the value of the <code>srcs</code> attribute.
    </p>

    </td>
  </tr>
                  <tr>
    <td id="filegroup.data">
      <code>data</code>
    </td>
    <td>
                <p><code>List of <a href="/versions/6.2.0/concepts/labels">labels</a>; optional</code></p>
                        The list of files needed by this rule at runtime.
    <p>
      Targets named in the <code>data</code> attribute will be added to the
      <code>runfiles</code> of this <code>filegroup</code> rule. When the
      <code>filegroup</code> is referenced in the <code>data</code> attribute of
      another rule its <code>runfiles</code> will be added to the <code>runfiles</code>
      of the depending rule. See the <a href="/versions/6.2.0/concepts/dependencies#data-dependencies">data dependencies</a>
      section and <a href="/versions/6.2.0/reference/be/common-definitions#common.data">general documentation of
      <code>data</code></a> for more information about how to depend on and use data files.
    </p>

    </td>
  </tr>
                                                                    <tr>
    <td id="filegroup.output_group">
      <code>output_group</code>
    </td>
    <td>
                <p><code>String; optional</code></p>
                        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.
    <p>An "output group" is a category of output artifacts of a target, specified in that
      rule's implementation.
    </p>

    </td>
  </tr>
                                                            </tbody>
</table> <h2 id="genquery"> genquery </h2> <pre class="rule-signature">genquery(<a href="#genquery.name">name</a>, <a href="common-definitions.html#typical.deps">deps</a>, <a href="common-definitions.html#typical.data">data</a>, <a href="common-definitions.html#common.compatible_with">compatible_with</a>, <a href="common-definitions.html#common.deprecation">deprecation</a>, <a href="common-definitions.html#common.distribs">distribs</a>, <a href="common-definitions.html#common.exec_compatible_with">exec_compatible_with</a>, <a href="common-definitions.html#common.exec_properties">exec_properties</a>, <a href="#genquery.expression">expression</a>, <a href="common-definitions.html#common.features">features</a>, <a href="common-definitions.html#typical.licenses">licenses</a>, <a href="#genquery.opts">opts</a>, <a href="common-definitions.html#common.restricted_to">restricted_to</a>, <a href="#genquery.scope">scope</a>, <a href="#genquery.strict">strict</a>, <a href="common-definitions.html#common.tags">tags</a>, <a href="common-definitions.html#common.target_compatible_with">target_compatible_with</a>, <a href="common-definitions.html#common.testonly">testonly</a>, <a href="common-definitions.html#common.visibility">visibility</a>)</pre> <p> <code>genquery()</code> runs a query specified in the <a href="/versions/6.2.0/reference/query">Blaze query language</a> and dumps the result into a file. </p> <p> In order to keep the build consistent, the query is allowed only to visit the transitive closure of the targets specified in the <code>scope</code> attribute. Queries violating this rule will fail during execution if <code>strict</code> is unspecified or true (if <code>strict</code> 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. </p> <p> The only difference between the queries allowed here and on the command line is that queries containing wildcard target specifications (e.g. <code>//pkg:*</code> or <code>//pkg:all</code>) are not allowed here. The reasons for this are two-fold: first, because <code>genquery</code> has to specify a scope to prevent targets outside the transitive closure of the query to influence its output; and, second, because <code>BUILD</code> files do not support wildcard dependencies (e.g. <code>deps=["//a/..."]</code> is not allowed). </p> <p> The genquery's output is ordered using <code>--order_output=full</code> in order to enforce deterministic output. <p> The name of the output file is the name of the rule. </p> <h4 id="genquery_examples">Examples</h4> <p> This example writes the list of the labels in the transitive closure of the specified target to a file. </p> <pre class="code"> genquery( name = "kiwi-deps", expression = "deps(//kiwi:kiwi_lib)", scope = ["//kiwi:kiwi_lib"], ) </pre> <h3 id="genquery_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 colspan="2">Attributes</th> </tr> </thead> <tbody> <tr> <td id="genquery.name"><code>name</code></td> <td> <p><code><a href="/versions/6.2.0/concepts/labels#target-names">Name</a>; required</code></p> <p>A unique name for this target.</p>
    </td>
  </tr>
                                                                                  <tr>
    <td id="genquery.expression">
      <code>expression</code>
    </td>
    <td>
                <p><code>String; required</code></p>
                        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 <code>:b</code> in this attribute in the file <code>a/BUILD</code> will refer to the
    target <code>//:b</code>.

    </td>
  </tr>
                                      <tr>
    <td id="genquery.opts">
      <code>opts</code>
    </td>
    <td>
                <p><code>List of strings; optional</code></p>
                        The options that are passed to the query engine. These correspond to the command line
    options that can be passed to <code>bazel query</code>. Some query options are not allowed
    here: <code>--keep_going</code>, <code>--query_file</code>, <code>--universe_scope</code>,
    <code>--order_results</code> and <code>--order_output</code>. Options not specified here
    will have their default values just like on the command line of <code>bazel query</code>.

    </td>
  </tr>
                            <tr>
    <td id="genquery.scope">
      <code>scope</code>
    </td>
    <td>
                <p><code>null; required</code></p>
                        The scope of the query. The query is not allowed to touch targets outside the transitive
    closure of these targets.

    </td>
  </tr>
                  <tr>
    <td id="genquery.strict">
      <code>strict</code>
    </td>
    <td>
                <p><code>Boolean; optional; default is True</code></p>
                        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.

    </td>
  </tr>
                                                  </tbody>
</table> <h2 id="genrule"> genrule </h2> <pre class="rule-signature">genrule(<a href="#genrule.name">name</a>, <a href="#genrule.srcs">srcs</a>, <a href="#genrule.outs">outs</a>, <a href="#genrule.cmd">cmd</a>, <a href="#genrule.cmd_bash">cmd_bash</a>, <a href="#genrule.cmd_bat">cmd_bat</a>, <a href="#genrule.cmd_ps">cmd_ps</a>, <a href="common-definitions.html#common.compatible_with">compatible_with</a>, <a href="common-definitions.html#common.deprecation">deprecation</a>, <a href="common-definitions.html#common.distribs">distribs</a>, <a href="common-definitions.html#common.exec_compatible_with">exec_compatible_with</a>, <a href="common-definitions.html#common.exec_properties">exec_properties</a>, <a href="#genrule.exec_tools">exec_tools</a>, <a href="#genrule.executable">executable</a>, <a href="common-definitions.html#common.features">features</a>, <a href="common-definitions.html#typical.licenses">licenses</a>, <a href="#genrule.local">local</a>, <a href="#genrule.message">message</a>, <a href="#genrule.output_licenses">output_licenses</a>, <a href="#genrule.output_to_bindir">output_to_bindir</a>, <a href="common-definitions.html#common.restricted_to">restricted_to</a>, <a href="common-definitions.html#common.tags">tags</a>, <a href="common-definitions.html#common.target_compatible_with">target_compatible_with</a>, <a href="common-definitions.html#common.testonly">testonly</a>, <a href="common-definitions.html#common.toolchains">toolchains</a>, <a href="#genrule.tools">tools</a>, <a href="common-definitions.html#common.visibility">visibility</a>)</pre> <p>A <code>genrule</code> generates one or more files using a user-defined Bash command.</p> <p> 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 <code>cc_*</code> rules, because all the heavy lifting has already been done for you. </p> <p> 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 host architecture (the two may be different). If you need a general purpose testing rule, use <a href="/versions/6.2.0/reference/be/shell.html#sh_test"><code>sh_test</code></a>. </p> <h4>Cross-compilation Considerations</h4> <p> <em>See <a href="/versions/6.2.0/docs/user-manual#configurations">the user manual</a> for more info about cross-compilation.</em> </p> <p> 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. </p> <p> The build system uses the host 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. </p> <p> For genrules, the build system ensures that dependencies are built appropriately: <code>srcs</code> are built (if necessary) for the <em>target</em> configuration, <code>tools</code> are built for the <em>host</em> configuration, and the output is considered to be for the <em>target</em> configuration. It also provides <a href="/versions/6.2.0/reference/be/make-variables"> "Make" variables</a> that genrule commands can pass to the corresponding tools. </p> <p> It is intentional that genrule defines no <code>deps</code> 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. </p> <h4>Special Cases</h4> <p> <i>Host-host compilation</i>: 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 host 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 <code>srcs</code> and <code>outs</code> of the first genrule for the host configuration instead of the target configuration. See <a href="/versions/6.2.0/docs/user-manual#configurations">the user manual</a> for more info. </p> <p> <i>JDK & C++ Tooling</i>: to use a tool from the JDK or the C++ compiler suite, the build system provides a set of variables to use. See <a href="/versions/6.2.0/reference/be/make-variables">"Make" variable</a> for details. </p> <h4>Genrule Environment</h4> <p> The genrule command is executed by a Bash shell that is configured to fail when a command or a pipeline fails, using <code>set -e -o pipefail</code>. </p> <p> The build tool executes the Bash command in a sanitized process environment that defines only core variables such as <code>PATH</code>, <code>PWD</code>, <code>TMPDIR</code>, 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 <code>PATH</code> environment variable.

Any change to the value of <code>PATH</code> will cause Bazel to re-execute the command on the next build.

<!-- See https://github.com/bazelbuild/bazel/issues/1142 --> </p> <p> 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. </p> <p> 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. </p> <h4>General Advice</h4> <ul> <li>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.</li> <li>Do use <code>$(location)</code> 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.</li> <li>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.</li> <li>Do make sure that the exit code correctly indicates success or failure of the genrule.</li> <li>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.</li> <li><code>$$</code> evaluates to a <code>$</code>, a literal dollar-sign, so in order to invoke a shell command containing dollar-signs such as <code>ls $(dirname $x)</code>, one must escape it thus: <code>ls $$(dirname $$x)</code>.</li> <li>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.</li> <li>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 <code>srcs</code> will avoid unintentionally picking up other outputs of the genrule, but can be tedious if the genrule produces many outputs.</li> </ul> <h4 id="genrule_examples">Examples</h4> <p> This example generates <code>foo.h</code>. 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. </p> <pre class="code"> genrule( name = "foo", srcs = [], outs = ["foo.h"], cmd = "./$(location create_foo.pl) &gt; \"$@\"", tools = ["create_foo.pl"], ) </pre> <p> The following example shows how to use a <a href="/versions/6.2.0/reference/be/general.html#filegroup"><code>filegroup</code> </a> and the outputs of another <code>genrule</code>. Note that using <code>$(SRCS)</code> instead of explicit <code>$(location)</code> directives would also work; this example uses the latter for sake of demonstration. </p> <pre class="code"> genrule( name = "concat_all_files", srcs = [ "//some:files", # a filegroup with multiple files in it ==> $(location<b>s</b>) "//other:gen", # a genrule with a single output ==> $(location) ], outs = ["concatenated.txt"], cmd = "cat $(locations //some:files) $(location //other:gen) > $@", ) </pre> <h3 id="genrule_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 colspan="2">Attributes</th> </tr> </thead> <tbody> <tr> <td id="genrule.name"><code>name</code></td> <td> <p><code><a href="/versions/6.2.0/concepts/labels#target-names">Name</a>; required</code></p> <p>A unique name for this target.</p>

You may refer to this rule by name in the <code>srcs</code> or <code>deps</code> section of other <code>BUILD</code> rules. If the rule generates source files, you should use the <code>srcs</code> attribute.

    </td>
  </tr>
            <tr>
    <td id="genrule.srcs">
      <code>srcs</code>
    </td>
    <td>
                <p><code>List of <a href="/versions/6.2.0/concepts/labels">labels</a>; optional</code></p>
                        A list of inputs for this rule, such as source files to process.
    <p>
      <em>This attributes is not suitable to list tools executed by the <code>cmd</code>; use
      the <a href="/versions/6.2.0/reference/be/general.html#genrule.tools"><code>tools</code></a> attribute for them instead.
      </em>
    </p>
    <p>
      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 <code>$(SRCS)</code>; alternatively the path of an individual
      <code>srcs</code> target <code>//x:y</code> can be obtained using <code>$(location
      //x:y)</code>, or using <code>$&lt;</code> provided it's the only entry in
      <code>srcs</code>.
    </p>

    </td>
  </tr>
                  <tr>
    <td id="genrule.outs">
      <code>outs</code>
    </td>
    <td>
                <p><code>List of <a href="/versions/6.2.0/concepts/build-ref#filename">filenames</a>; required; <a href="common-definitions.html#configurable-attributes">nonconfigurable</a></code></p>
                        A list of files generated by this rule.
    <p>
      Output files must not cross package boundaries.
      Output filenames are interpreted as relative to the package.
    </p>
    <p>
      If the <code>executable</code> flag is set, <code>outs</code> must contain exactly one
      label.
    </p>
    <p>
      The genrule command is expected to create each output file at a predetermined location.
      The location is available in <code>cmd</code> using <a
      href="/versions/6.2.0/reference/be/make-variables#predefined_genrule_variables">genrule-specific "Make"
      variables</a> (<code>$@</code>, <code>$(OUTS)</code>, <code>$(@D)</code> or <code>
      $(RULEDIR)</code>) or using <a href="/versions/6.2.0/reference/be/make-variables#predefined_label_variables">
      <code>$(location)</code></a> substitution.
    </p>

    </td>
  </tr>
                  <tr>
    <td id="genrule.cmd">
      <code>cmd</code>
    </td>
    <td>
                <p><code>String; optional</code></p>
                        The command to run.
    Subject to <a href="/versions/6.2.0/reference/be/make-variables#predefined_label_variables"><code>$(location)
    </code></a> and <a href="/versions/6.2.0/reference/be/make-variables">"Make" variable</a> substitution.
    <ol>
      <li>
        First <a href="/versions/6.2.0/reference/be/make-variables#predefined_label_variables"><code>$(location)
        </code></a> substitution is applied, replacing all occurrences of <code>$(location <i>
        label</i>)</code> and of <code>$(locations <i>label</i>)</code> (and similar
        constructions using related variables <code>execpath</code>, <code>execpaths</code>,
        <code>rootpath</code> and <code>rootpaths</code>).
      </li>
      <li>
        Next, <a href="/versions/6.2.0/reference/be/make-variables">"Make" variables</a> are expanded. Note that
        predefined variables <code>$(JAVA)</code>, <code>$(JAVAC)</code> and
        <code>$(JAVABASE)</code> expand under the <i>host</i> configuration, so Java invocations
        that run as part of a build step can correctly load shared libraries and other
        dependencies.
      </li>
      <li>
        Finally, the resulting command is executed using the Bash shell. If its exit code is
        non-zero the command is considered to have failed.
      </li>
    </ol>
    This is the fallback of <code>cmd_bash</code>, <code>cmd_ps</code> and <code>cmd_bat</code>,
    if none of them are applicable.
    </p>
    <p>
    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 (<code>cmd</code>, <code>cmd_bash</code>, <code>cmd_ps</code>,
    <code>cmd_bat</code>).
    </p>

    </td>
  </tr>
                  <tr>
    <td id="genrule.cmd_bash">
      <code>cmd_bash</code>
    </td>
    <td>
                <p><code>String; optional</code></p>
                        The Bash command to run.
    <p> This attribute has higher priority than <code>cmd</code>. The command is expanded and
        runs in the exact same way as the <code>cmd</code> attribute.
    </p>

    </td>
  </tr>
                  <tr>
    <td id="genrule.cmd_bat">
      <code>cmd_bat</code>
    </td>
    <td>
                <p><code>String; optional</code></p>
                        The Batch command to run on Windows.
    <p> This attribute has higher priority than <code>cmd</code> and <code>cmd_bash</code>.
        The command runs in the similar way as the <code>cmd</code> attribute, with the
        following differences:
    </p>
    <ul>
      <li>
        This attribute only applies on Windows.
      </li>
      <li>
        The command runs with <code>cmd.exe /c</code> with the following default arguments:
        <ul>
          <li>
            <code>/S</code> - strip first and last quotes and execute everything else as is.
          </li>
          <li>
            <code>/E:ON</code> - enable extended command set.
          </li>
          <li>
            <code>/V:ON</code> - enable delayed variable expansion
          </li>
          <li>
            <code>/D</code> - ignore AutoRun registry entries.
          </li>
        </ul>
      </li>
      <li>
        After <a href="/versions/6.2.0/reference/be/make-variables#predefined_label_variables">$(location)</a> and
        <a href="/versions/6.2.0/reference/be/make-variables">"Make" variable</a> substitution, the paths will be
        expanded to Windows style paths (with backslash).
      </li>
    </ul>

    </td>
  </tr>
                  <tr>
    <td id="genrule.cmd_ps">
      <code>cmd_ps</code>
    </td>
    <td>
                <p><code>String; optional</code></p>
                        The Powershell command to run on Windows.
    <p> This attribute has higher priority than <code>cmd</code>, <code>cmd_bash</code> and
        <code>cmd_bat</code>. The command runs in the similar way as the <code>cmd</code>
        attribute, with the following differences:
    </p>
    <ul>
      <li>
        This attribute only applies on Windows.
      </li>
      <li>
        The command runs with <code>powershell.exe /c</code>.
      </li>
    </ul>
    <p> 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.
    </p>
    <ul>
      <li>
        <code>Set-ExecutionPolicy -Scope CurrentUser RemoteSigned</code> - allow running
        unsigned scripts.
      </li>
      <li>
        <code>$errorActionPreference='Stop'</code> - In case there are multiple commands
        separated by <code>;</code>, the action exits immediately if a Powershell CmdLet fails,
        but this does <strong>NOT</strong> work for external command.
      </li>
      <li>
        <code>$PSDefaultParameterValues['*:Encoding'] = 'utf8'</code> - change the default
        encoding from utf-16 to utf-8.
      </li>
    </ul>

    </td>
  </tr>
                                                                    <tr>
    <td id="genrule.exec_tools">
      <code>exec_tools</code>
    </td>
    <td>
                <p><code>List of <a href="/versions/6.2.0/concepts/labels">labels</a>; optional</code></p>
                        A list of <i>tool</i> dependencies for this rule. This behaves exactly like the
    <a href="#genrule.tools"><code>tools</code></a> attribute, except that these dependencies
    will be configured for the rule's execution platform instead of the host configuration.
    This means that dependencies in <code>exec_tools</code> are not subject to the same
    limitations as dependencies in <code>tools</code>. In particular, they are not required to
    use the host configuration for their own transitive dependencies. See
    <a href="#genrule.tools"><code>tools</code></a> for further details.

    <p>
      The Blaze team is migrating all uses of <code>tools</code> to use <code>exec_tools</code>
      semantics. Users are encouraged to prefer <code>exec_tools</code> to <code>tools</code>
      where this does not cause any issues. After the functional migration is complete, we may
      rename <code>exec_tools</code> to <code>tools</code>.  You will receive a deprecation
      warning and migration instructions before this happens.
    </p>

    </td>
  </tr>
                  <tr>
    <td id="genrule.executable">
      <code>executable</code>
    </td>
    <td>
                <p><code>Boolean; optional; <a href="common-definitions.html#configurable-attributes">nonconfigurable</a>; default is False</code></p>
                        Declare output to be executable.
    <p>
      Setting this flag to True means the output is an executable file and can be run using the
      <code>run</code> command. The genrule must produce exactly one output in this case.
      If this attribute is set, <code>run</code> will try executing the file regardless of
      its content.
    </p>
    <p>Declaring data dependencies for the generated executable is not supported.</p>

    </td>
  </tr>
                                      <tr>
    <td id="genrule.local">
      <code>local</code>
    </td>
    <td>
                <p><code>Boolean; optional; default is False</code></p>
                        <p>
      If set to True, this option forces this <code>genrule</code> to run using the "local"
      strategy, which means no remote execution, no sandboxing, no persistent workers.
    </p>
    <p>
      This is equivalent to providing 'local' as a tag (<code>tags=["local"]</code>).
    </p>

    </td>
  </tr>
                  <tr>
    <td id="genrule.message">
      <code>message</code>
    </td>
    <td>
                <p><code>String; optional</code></p>
                        A progress message.
    <p>
      A progress message that will be printed as this build step is executed. By default, the
      message is "Generating <i>output</i>" (or something equally bland) but you may provide a
      more specific one. Use this attribute instead of <code>echo</code> or other print
      statements in your <code>cmd</code> command, as this allows the build tool to control
      whether such progress messages are printed or not.
    </p>

    </td>
  </tr>
                  <tr>
    <td id="genrule.output_licenses">
      <code>output_licenses</code>
    </td>
    <td>
                <p><code>Licence type; optional</code></p>
                        See <a href="/versions/6.2.0/reference/be/common-definitions#binary.output_licenses"><code>common attributes
    </code></a>

    </td>
  </tr>
                  <tr>
    <td id="genrule.output_to_bindir">
      <code>output_to_bindir</code>
    </td>
    <td>
                <p><code>Boolean; optional; <a href="common-definitions.html#configurable-attributes">nonconfigurable</a>; default is False</code></p>
                        <p>
      If set to True, this option causes output files to be written into the <code>bin</code>
      directory instead of the <code>genfiles</code> directory.
    </p>

    </td>
  </tr>
                                                                    <tr>
    <td id="genrule.tools">
      <code>tools</code>
    </td>
    <td>
                <p><code>List of <a href="/versions/6.2.0/concepts/labels">labels</a>; optional</code></p>
                        A list of <i>tool</i> dependencies for this rule. See the definition of
    <a href="/versions/6.2.0/concepts/build-ref#deps">dependencies</a> for more information. 

    <p>
      The build system ensures these prerequisites are built before running the genrule command;
      they are built using the <a href='/versions/6.2.0/contribute/guide#configurations'><i>host</i>
      configuration</a>, since these tools are executed as part of the build. The path of an
      individual <code>tools</code> target <code>//x:y</code> can be obtained using
      <code>$(location //x:y)</code>.
    </p>
    <p>
      Any <code>*_binary</code> or tool to be executed by <code>cmd</code> must appear in this
      list, not in <code>srcs</code>, to ensure they are built in the correct configuration.
    </p>

    </td>
  </tr>
                    </tbody>
</table> <h2 id="test_suite"> test_suite </h2> <pre class="rule-signature">test_suite(<a href="#test_suite.name">name</a>, <a href="common-definitions.html#common.compatible_with">compatible_with</a>, <a href="common-definitions.html#common.deprecation">deprecation</a>, <a href="common-definitions.html#common.distribs">distribs</a>, <a href="common-definitions.html#common.features">features</a>, <a href="common-definitions.html#typical.licenses">licenses</a>, <a href="common-definitions.html#common.restricted_to">restricted_to</a>, <a href="#test_suite.tags">tags</a>, <a href="common-definitions.html#common.target_compatible_with">target_compatible_with</a>, <a href="common-definitions.html#common.testonly">testonly</a>, <a href="#test_suite.tests">tests</a>, <a href="common-definitions.html#common.visibility">visibility</a>)</pre> <p> A <code>test_suite</code> 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 <code>blaze test</code> command respects this sort of organization: For an invocation like <code>blaze test //some/test:suite</code>, Blaze first enumerates all test targets transitively included by the <code>//some/test:suite</code> target (we call this "test_suite expansion"), then Blaze builds and tests those targets. </p> <h4 id="test_suite_examples">Examples</h4> <p>A test suite to run all of the small tests in the current package.</p> <pre class="code"> test_suite( name = "small_tests", tags = ["small"], ) </pre> <p>A test suite that runs a specified set of tests:</p> <pre class="code"> test_suite( name = "smoke_tests", tests = [ "system_unittest", "public_api_unittest", ], ) </pre> <p>A test suite to run all tests in the current package which are not flaky.</p> <pre class="code"> test_suite( name = "non_flaky_test", tags = ["-flaky"], ) </pre> <h3 id="test_suite_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 colspan="2">Attributes</th> </tr> </thead> <tbody> <tr> <td id="test_suite.name"><code>name</code></td> <td> <p><code><a href="/versions/6.2.0/concepts/labels#target-names">Name</a>; required</code></p> <p>A unique name for this target.</p>
    </td>
  </tr>
                                                                        <tr>
    <td id="test_suite.tags">
      <code>tags</code>
    </td>
    <td>
                <p><code>List of strings; optional; <a href="common-definitions.html#configurable-attributes">nonconfigurable</a></code></p>
                        List of text tags such as "small" or "database" or "-flaky". Tags may be any valid string.
    <p>
      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.
    </p>
    <p>
      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.
    </p>
    <p>
      Only test rules that match <b>all</b> of the positive tags and <b>none</b> 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).
    </p>
    <p>
      The <code>manual</code> tag keyword is treated differently than the above by the
      "test_suite expansion" performed by the <code>blaze test</code> command on invocations
      involving wildcard
      <a href="https://bazel.build/versions/6.2.0/docs/build#specifying-build-targets">target patterns</a>.
      There, <code>test_suite</code> targets tagged "manual" are filtered out (and thus not
      expanded). This behavior is consistent with how <code>blaze build</code> and
      <code>blaze test</code> handle wildcard target patterns in general. Note that this is
      explicitly different from how <code>blaze query 'tests(E)'</code> behaves, as suites are
      always expanded by the <code>tests</code> query function, regardless of the
      <code>manual</code> tag.
    </p>
    <p>
      Note that a test's <code>size</code> is considered a tag for the purpose of filtering.
    </p>
    <p>
      If you need a <code>test_suite</code> that contains tests with mutually exclusive tags
      (e.g. all small and medium tests), you'll have to create three <code>test_suite</code>
      rules: one for all small tests, one for all medium tests, and one that includes the
      previous two.
    </p>

    </td>
  </tr>
                                      <tr>
    <td id="test_suite.tests">
      <code>tests</code>
    </td>
    <td>
                <p><code>List of <a href="/versions/6.2.0/concepts/labels">labels</a>; optional; <a href="common-definitions.html#configurable-attributes">nonconfigurable</a></code></p>
                        A list of test suites and test targets of any language.
    <p>
      Any <code>*_test</code> is accepted here, independent of the language. No
      <code>*_binary</code> targets are accepted however, even if they happen to run a test.
      Filtering by the specified <code>tags</code> is only done for tests listed directly in
      this attribute. If this attribute contains <code>test_suite</code>s, the tests inside
      those will not be filtered by this <code>test_suite</code> (they are considered to be
      filtered already).
    </p>
    <p>
      If the <code>tests</code> attribute is unspecified or empty, the rule will default to
      including all test rules in the current BUILD file that are not tagged as
      <code>manual</code>. These rules are still subject to <code>tag</code> filtering.
    </p>

    </td>
  </tr>
                    </tbody>
</table> <!-- Generated footer --> </body> </html>