Cargo

cargo_dep_env

cargo_dep_env(name, src, out_dir)

A rule for generating variables for dependent cargo_build_scripts without a build script. This is useful for using Bazel rules instead of a build script, while also generating configuration information for build scripts which depend on this crate.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
srcFile containing additional environment variables to set for build scripts of direct dependencies.

This has the same effect as a cargo_build_script which prints cargo:VAR=VALUE lines, but without requiring a build script.

This files should contain a single variable per line, of format NAME=value, and newlines may be included in a value by ending a line with a trailing back-slash (\\).
Labelrequired
out_dirFolder containing additional inputs when building all direct dependencies.

This has the same effect as a cargo_build_script which prints puts files into $OUT_DIR, but without requiring a build script.
LabeloptionalNone

cargo_build_script

cargo_build_script(name, edition, crate_name, crate_root, srcs, crate_features, version, deps,
                   link_deps, proc_macro_deps, build_script_env, data, compile_data, tools, links,
                   rundir, rustc_env, rustc_env_files, rustc_flags, visibility, tags, aliases,
                   pkg_name, kwargs)

Compile and execute a rust build script to generate build attributes

This rules take the same arguments as rust_binary.

Example:

Suppose you have a crate with a cargo build script build.rs:

[workspace]/
    hello_lib/
        BUILD
        build.rs
        src/
            lib.rs

Then you want to use the build script in the following:

hello_lib/BUILD:

package(default_visibility = ["//visibility:public"])

load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library")
load("@rules_rust//cargo:defs.bzl", "cargo_build_script")

# This will run the build script from the root of the workspace, and
# collect the outputs.
cargo_build_script(
    name = "build_script",
    srcs = ["build.rs"],
    # Optional environment variables passed during build.rs compilation
    rustc_env = {
       "CARGO_PKG_VERSION": "0.1.2",
    },
    # Optional environment variables passed during build.rs execution.
    # Note that as the build script's working directory is not execroot,
    # execpath/location will return an absolute path, instead of a relative
    # one.
    build_script_env = {
        "SOME_TOOL_OR_FILE": "$(execpath @tool//:binary)"
    },
    # Optional data/tool dependencies
    data = ["@tool//:binary"],
)

rust_library(
    name = "hello_lib",
    srcs = [
        "src/lib.rs",
    ],
    deps = [":build_script"],
)

The hello_lib target will be build with the flags and the environment variables declared by the build script in addition to the file generated by it.

PARAMETERS

NameDescriptionDefault Value
nameThe name for the underlying rule. This should be the name of the package being compiled, optionally with a suffix of _bs. Otherwise, you can set the package name via pkg_name.none
editionThe rust edition to use for the internal binary crate.None
crate_nameCrate name to use for build script.None
crate_rootThe file that will be passed to rustc to be used for building this crate.None
srcsSouce files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are made.[]
crate_featuresA list of features to enable for the build script.[]
versionThe semantic version (semver) of the crate.None
depsThe build-dependencies of the crate.[]
link_depsThe subset of the (normal) dependencies of the crate that have the links attribute and therefore provide environment variables to this build script.[]
proc_macro_depsList of rust_proc_macro targets used to build the script.[]
build_script_envEnvironment variables for build scripts.{}
dataFiles needed by the build script.[]
compile_dataFiles needed for the compilation of the build script.[]
toolsTools (executables) needed by the build script.[]
linksName of the native library this crate links against.None
rundirA directory to cd to before the cargo_build_script is run. This should be a path relative to the exec root.

The default behaviour (and the behaviour if rundir is set to the empty string) is to change to the relative path corresponding to the cargo manifest directory, which replicates the normal behaviour of cargo so it is easy to write compatible build scripts.

If set to ., the cargo build script will run in the exec root.
None
rustc_envEnvironment variables to set in rustc when compiling the build script.{}
rustc_env_filesFiles containing additional environment variables to set for rustc when building the build script.[]
rustc_flagsList of compiler flags passed to rustc.[]
visibilityVisibility to apply to the generated build script output.None
tags(list of str, optional): Tags to apply to the generated build script output.None
aliasesRemap crates to a new name or moniker for linkage to this target. These are other rust_library targets and will be presented as the new name given.None
pkg_nameOverride the package name used for the build script. This is useful if the build target name gets too long otherwise.None
kwargsForwards to the underlying rust_binary rule. An exception is the compatible_with attribute, which shouldn't be forwarded to the rust_binary, as the rust_binary is only built and used in exec mode. We propagate the compatible_with attribute to the _build_scirpt_run target.none

cargo_env

cargo_env(env)

A helper for generating platform specific environment variables

load("@rules_rust//rust:defs.bzl", "rust_common")
load("@rules_rust//cargo:defs.bzl", "cargo_bootstrap_repository", "cargo_env")

cargo_bootstrap_repository(
    name = "bootstrapped_bin",
    cargo_lockfile = "//:Cargo.lock",
    cargo_toml = "//:Cargo.toml",
    srcs = ["//:resolver_srcs"],
    version = rust_common.default_version,
    binary = "my-crate-binary",
    env = {
        "x86_64-unknown-linux-gnu": cargo_env({
            "FOO": "BAR",
        }),
    },
    env_label = {
        "aarch64-unknown-linux-musl": cargo_env({
            "DOC": "//:README.md",
        }),
    }
)

PARAMETERS

NameDescriptionDefault Value
envA map of environment variablesnone

RETURNS

str: A json encoded string of the environment variables

cargo_bootstrap_repository

cargo_bootstrap_repository(name, srcs, binary, build_mode, cargo_config, cargo_lockfile, cargo_toml,
                           env, env_label, repo_mapping, rust_toolchain_cargo_template,
                           rust_toolchain_rustc_template, timeout, version)

A rule for bootstrapping a Rust binary using Cargo

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this repository.Namerequired
srcsSouce files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are madeList of labelsoptional[]
binaryThe binary to build (the --bin parameter for Cargo). If left empty, the repository name will be used.Stringoptional""
build_modeThe build mode the binary should be built withStringoptional"release"
cargo_configThe path of the Cargo configuration (Config.toml) file.LabeloptionalNone
cargo_lockfileThe lockfile of the crate_universe resolverLabelrequired
cargo_tomlThe path of the Cargo.toml file.Labelrequired
envA mapping of platform triple to a set of environment variables. See cargo_env for usage details. Additionally, the platform triple * applies to all platforms.Dictionary: String -> Stringoptional{}
env_labelA mapping of platform triple to a set of environment variables. This attribute differs from env in that all variables passed here must be fully qualified labels of files. See cargo_env for usage details. Additionally, the platform triple * applies to all platforms.Dictionary: String -> Stringoptional{}
repo_mappingIn WORKSPACE context only: 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).

This attribute is not supported in MODULE.bazel context (when invoking a repository rule inside a module extension's implementation function).
Dictionary: String -> Stringoptional
rust_toolchain_cargo_templateThe template to use for finding the host cargo binary. {version} (eg. '1.53.0'), {triple} (eg. 'x86_64-unknown-linux-gnu'), {arch} (eg. 'aarch64'), {vendor} (eg. 'unknown'), {system} (eg. 'darwin'), {channel} (eg. 'stable'), and {tool} (eg. 'rustc.exe') will be replaced in the string if present.Stringoptional"@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}"
rust_toolchain_rustc_templateThe template to use for finding the host rustc binary. {version} (eg. '1.53.0'), {triple} (eg. 'x86_64-unknown-linux-gnu'), {arch} (eg. 'aarch64'), {vendor} (eg. 'unknown'), {system} (eg. 'darwin'), {channel} (eg. 'stable'), and {tool} (eg. 'rustc.exe') will be replaced in the string if present.Stringoptional"@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}"
timeoutMaximum duration of the Cargo build command in secondsIntegeroptional600
versionThe version of Rust the currently registered toolchain is using. Eg. 1.56.0, or nightly/2021-09-08Stringoptional"1.83.0"