bazelbuild / rules_rust

Rust rules for Bazel
https://bazelbuild.github.io/rules_rust/
Apache License 2.0
625 stars 399 forks source link

Read CARGO_PKG_VERSION from specified Cargo.toml #553

Open wchargin opened 3 years ago

wchargin commented 3 years ago

Currently, you can pass rust_binary(version = "0.1.0") to build with CARGO_PKG_VERSION=0.1.0. But the version must be a value known at analysis time. It would be nice to be able to pull this version from an existing Cargo.toml file so that a binary can be dual-built with both Bazel and Cargo.

This is useful, for instance, when using clap::crate_version!() to set the version string in a command-line app. Currently, I’m hard-coding a version string duplicated in both Cargo.toml and cli.rs just so that Bazel can have access to the right version.

I contemplated trying to use a genrule that extracts the package version from Cargo.toml at build time, but I don’t think that it would work. We could generate a file version.txt that contains just the version, but I don’t see how to feed that into ctx.attr.version.

illicitonion commented 3 years ago

I put together https://github.com/bazelbuild/rules_rust/pull/466 a while ago but then never followed up - would that serve your needs?

wchargin commented 3 years ago

Yeah, that looks great! It looks like it would require using a genrule to extract the actual version from Cargo.toml, so it would be evven nicer for my purposes to allow version_cargo_toml = ":Cargo.toml", but your approach is clearly more generally useful, so I’m happy to write the genrule on my side.

(I missed that PR in my search—thanks for flagging it!)

wchargin commented 3 years ago

Cross-referencing: upon more reflection, I wonder whether it would make more sense to expose this from cargo-raze, since that’s the part of the stack that’s aware of the “Bazel/Cargo dual-build” situation. I’ve filed google/cargo-raze#357 accordingly.

cameron-martin commented 1 week ago

Looks like you can achieve this using the rustc_env_files attribute (see the related example), although it is still a bit clunky. You can see an example of how I do it here: https://github.com/cameron-martin/bazel-lsp/commit/c069c2db00f066f071f054732336de7f554d661f