Programmatically set package version in Cargo.toml to a git commit/tag

Is there a convenient way to programmatically set the package version in Cargo.toml? The use case, is for continuous integration tests, in which multiple test releases are created, but with different versions, set to the commit or tag, that triggered the continuous integration step. Thank you.

UPDATE
Adding some details, to make the question clearer. Given the following Cargo.toml:

[package]
name = "foo"
version = "0.1.0"
edition = "2021"
...

When running CI, I'd like to set version to something like 0.1.0-{commit}, and publish it to some testing site. This way, multiple pull requests with version = 0.1.0, can be published to a testing site, and not collide with each other, because in the CI phase, the version would be programmatically changed to 0.1.0-{commit}.

2 Likes

If using a [patch] section is acceptable for your use case, then you can simply append the following to the file Cargo.toml.

[patch.crates-io]
baz = { git = 'https://github.com/example/patched-baz', rev = 'commit hash here' }

If the package isn't on crates-io, the syntax is somewhat different. See this page for more details.

Thanks for the help! I will update my question to make it clearer. What I'm looking for is to programmatically set the version field in:

[package]
name = "foo"
version = "0.1.0"
edition = "2021"

When running CI, I'd like to set version to something like 0.1.0-{commit}, and publish it to some testing site. This way, multiple pull requests with version = 0.1.0, can be published to a testing site, and not collide with each other, because in the CI phase, the version would be programmatically changed to 0.1.0-{commit}.

The following command changes the version by adding -foo at the end.

sed -i '0,/version/s/^version = "\([0-9.]*\)"$/version = "\1-foo"/' Cargo.toml
1 Like

If you're looking for something a bit more principled: https://crates.io/crates/cargo-edit#cargo-set-version

Note that you'll need to use cargo publish --allow-dirty either way.

1 Like

There's also the toml_edit library which you can use to make arbitrary modifications to TOML files in a structure-based fashion rather than text-replacement. It's what cargo-edit uses internally, and it might be useful if you end up wanting to make other tweaks.

2 Likes