Add `root_path` attribute for directory crate roots (#4142)

Allows specifying `root_path` when the crate root (`srcs` entrypoint) is
a directory artifact (`TreeArtifact`). This enables rules_rust targets
(`rust_library`, `rust_binary`, `rust_test`, etc.) to consume directory
artifacts produced by upstream rules and correctly construct the path to
the crate root (`lib.rs` / `main.rs`).

We use something like this internally to build standard libraries from
sources distributed as .zip source archives: a custom rule extracts the
contents into a generated directory artifact, which then the rust rules
can consume as sources.

This may be helpful to achieve the request from
https://github.com/bazelbuild/rules_rust/issues/3757, where the user is
trying to consume a directory of generated sources.

* Adds `root_path` attribute to `_COMMON_ATTRS` and `CrateInfo`
provider.
* Updates `rustc_compile_action` argument construction (`rustc.bzl`) to
join `crate_info.root.path` with `root_path` when
`crate_info.root.is_directory` is true.
* Adds a unit and build test case under `test/root_path/` using a custom
rule that packages its `srcs` as a directory artifact (`TreeArtifact`)
and compiles a `rust_library` and `rust_test` from it.

I have taken special care in the rustc argument construction to ensure
it is compatible with the new [bazel path remapping
guidelines](https://github.com/bazelbuild/bazel/discussions/22658).

While here, added a few checks in the rules for combinations of `srcs`,
`crate` and `crate_root` attributes that don't make sense and would
cause compilation to fail later anyways.
10 files changed
tree: 227edc9096ee349f5e4871486e43d66b04301329
  1. .bazelci/
  2. .bcr/
  3. .github/
  4. cargo/
  5. crate_universe/
  6. docs/
  7. examples/
  8. extensions/
  9. ffi/
  10. nix/
  11. rust/
  12. test/
  13. tools/
  14. util/
  15. .bazelignore
  16. .bazelrc
  17. .clang-format
  18. .clippy.toml
  19. .envrc
  20. .gitattributes
  21. .gitignore
  22. .pre-commit-config.yaml
  23. .prettierrc.toml
  24. .rustfmt.toml
  25. .typos.toml
  26. ARCHITECTURE.md
  27. AUTHORS
  28. BUILD.bazel
  29. CODEOWNERS
  30. COMPATIBILITY.md
  31. CONTRIBUTING.md
  32. CONTRIBUTORS
  33. LICENSE.txt
  34. MODULE.bazel
  35. README.md
  36. version.bzl
  37. WORKSPACE.bazel
README.md

Rust Rules

  • Postsubmit Build status

Overview

This repository provides rules for building Rust projects with Bazel.

Starter repo

The fastest way to try this in an empty project is to click the green “Use this template” button on https://github.com/bazel-starters/rust.

Community

General discussions and announcements take place in the GitHub Discussions, but there are additional places where community members gather to discuss rules_rust.

Documentation

Please refer to the full documentation.