How to externalize the version of a dependency in cargo.toml

Hi need to externalize the version of a dependency in cargo.toml
something like this below.
proxy-wasm = { $WASM_VERSION}

$WASM_VERSION can be part of env variable or defined in a properties file.

My requirement is, i have root directory, which has multiple sub directories. Each sub directory has multiple rust modules/package. I need to ensure that all modules are using same version of the dependency.

Using workspace is not an option for me because of the kind of setup I have.

Toml has no syntax for environment variable interpolation, nor does Cargo support this. There is a ton of cargo environment variables for overriding stuff, but nothing for overriding dependencies like that.

You could achieve something like this with an extra layer of templating on top of Cargo.toml with your preferred templating engine. I personally would either go super fancy and use Jsonnet (when you need to specify many versions from the environment) or super easy with a minimal sed-based setup, like:

Cargo.toml.template:

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

[dependencies]
uuid = "$UUID_VERSION"

Then I'd generate the Cargo.toml file by running

> UUID_VERSION="^1"
> sed s/\$UUID_VERSION/$UUID_VERSION/g Cargo.toml.template > Cargo.toml

to create

Cargo.toml:

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

[dependencies]
uuid = "^1"

Obviously, if you'd update your dependency you'd have to re-run this command for every of your packages to re-generate the correct Cargo.toml file.

I took inspiration for the sed-based setup from this SO post.

2 Likes

Thanks for the response. sed-based solution works. Seems like externalizing in cargo.toml.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.