Hi,
Sorry if this has been discussed before, I couldn't find anything in the search or in Rustlang issues.
Should the env! macro cause a rebuild if the value of the env var changes?
I tried this simple example:
fn main() {
println!("Hello, world! {:?}", env!("BUILD_NUMBER"));
}
BUILD_NUMBER=1 cargo build
BUILD_NUMBER=2 cargo build
Produces a binary the writes
Hello, world! "1"
So it's not rebuilt with the new env var value.
(Tried using a recent nightly and latest stable)
Thanks
Andy
2 Likes
Though env!
is computed at compile time, if you don't modify any of the text of the file, then Cargo will not even kick off a compile, so I wouldn't expect it to, no.
kornel
June 11, 2018, 9:11pm
3
There's rerun-if-changed-env but beware of side effects:
https://github.com/rust-lang/cargo/issues/4587
1 Like
We use env vars and rerun-if-changed quite extensively throughout our build, sounds like we need to have a good look at what is actually built when these change, as we've made some invalid assumptions.
Thanks for your help @steveklabnikand @kornel .
For anyone else who runs into this issue, this is how we solved it in the end:
Adding a build.rs:
use std::fs;
use std::io::Write;
use std::path::Path;
pub fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=BUILD_NUMBER");
let mut fout = fs::File::create(Path::new("./src/build_number.rs")).unwrap();
fout.write_all(format!(
"pub const BUILD_NUMBER: &'static str = \"{}\";",
::std::env::var("BUILD_NUMBER").unwrap_or("local".to_string())
).as_bytes()).unwrap();
}
Then adding mod build_number;
to the lib.rs and referencing the const string.