Dynamically Specifying Crate Version

I am integrating a new Rust component into a pre-existing, non-Rust repository with a well-established versioning and release strategy (think version.txt or GitVersion).

Rather than manually updating my Rust program's Cargo.toml each time we prepare for release, I'm wondering if there is some way to dynamically override the version number at build time. For example:

cargo build --my-custom-version-number 1.2.3

Obviously such a flag doesn't exist today. I'm wondering if anybody out there is in a similar situation and knows of a solution or workaround. Barring that, would there be any interest in adding such a flag to Cargo?

What specifically want to achieve with overriding the version number? Crate's version number is mostly irrelevant during the build. I think the only think it affects is the CRATE_VERSION env var that build script sees, and that's it.

The main use case I have in mind is embedding the version number into the binary so that users and other tools can easily determine the version they have. For instance, using clap's automatic --version flag.

Sounds like a small thing, but in practice I've found simple version checks like this to be invaluable in environments with lots of proprietary/internal tooling that changes often.

I suppose as a workaround, I could ignore the env vars passed by Cargo and use something like MY_CUSTOM_VERSION to use that to configure clap. Just thought it would be nice if there were a first-class way to plumb the version.

It sounds like you already have a build system that is invoking cargo. In that case you could use sed to change what version is written in the Cargo.toml. For example, to update it to 0.7.3

sed -i 's/version = "[0-9.]*"$/version = "0.7.3"/' Cargo.toml

Is the Rust code part of that larger repository or is your Rust component a separate crate/repo that's used in the larger repo? If the latter, I've found cargo-release works quite well and simplifies manual editing/git tagging.

It essentially:

  • bumps up major/minor/patch version in Cargo.toml
  • creates a new release commit
  • it optionally git-tags that commit
  • it creates a new dev/alpha version in Cargo.toml which is committed as well to main/master.

It can also help with change notes/release notes which is also handy in my use case.