Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set environment variables with Cargo?

Tags:

I have a dependency listed in Cargo.toml that needs a specific environment variable set. I can run export FOO=bar in bash and all works well, but for the life of me I can't figure out how to export this environment variable at compile time with Cargo. I've tried setting the environment variable in build.rs via std::env, Command, and println!, all to no effect:

// build.rs fn main() {     Command::new("ls")         .env("FOO", "bar")         .spawn()         .expect("ls command failed to start"); } 
// build.rs fn main() {     std::env::set_var("FOO", "bar"); } 
// build.rs fn main() {     println!("cargo:rustc-env=FOO=bar"); } 
like image 944
mandeep Avatar asked Jul 13 '19 07:07

mandeep


People also ask

How do you set environment variables?

Windows Environment Variables Do so by pressing the Windows and R key on your keyboard at the same time. Type sysdm. cpl into the input field and hit Enter or press Ok. In the new window that opens, click on the Advanced tab and afterwards on the Environment Variables button in the bottom right of the window.

How do I set environment variables in rust?

Set an environment variable in Rust You can set an environment variable (for the scope of the currently running process) using the standard library too. To do so, we use env::set_var(key, value) .

How do I set an environment variable in export?

To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").


1 Answers

Since Cargo 1.56, you can use the configurable-env feature via the [env] section in config.toml. This is not the same file as Cargo.toml, but it can still be set per project:

[env] FOO = "bar" PATH_TO_SOME_TOOL = { value = "bin/tool", relative = true } USERNAME = { value = "test_user", force = true } 

Environment variables set in this section will be applied to the environment of any processes executed by Cargo.

relative means the variable represents a path relative to the location of the directory that contains the .cargo/ directory that contains the config.toml file.

force means the variable can override an existing environment variable.

For more information about the history of this feature, see the related GitHub issue.

like image 176
Pâris Douady Avatar answered Sep 20 '22 19:09

Pâris Douady