I host a Rust project in git repository and I want to make it print the version on some command. How can I include the version into the program? I thought that the build script could set environment variables which can be used while compiling the project itself, but it does not work:
build.rs:
use std::env;
fn get_git_hash() -> Option<String> {
use std::process::Command;
let branch = Command::new("git")
.arg("rev-parse")
.arg("--abbrev-ref")
.arg("HEAD")
.output();
if let Ok(branch_output) = branch {
let branch_string = String::from_utf8_lossy(&branch_output.stdout);
let commit = Command::new("git")
.arg("rev-parse")
.arg("--verify")
.arg("HEAD")
.output();
if let Ok(commit_output) = commit {
let commit_string = String::from_utf8_lossy(&commit_output.stdout);
return Some(format!("{}, {}",
branch_string.lines().next().unwrap_or(""),
commit_string.lines().next().unwrap_or("")))
} else {
panic!("Can not get git commit: {}", commit_output.unwrap_err());
}
} else {
panic!("Can not get git branch: {}", branch.unwrap_err());
}
None
}
fn main() {
if let Some(git) = get_git_hash() {
env::set_var("GIT_HASH", git);
}
}
src/main.rs:
pub const GIT_HASH: &'static str = env!("GIT_HASH");
fm main() {
println!("Git hash: {}", GIT_HASH);
}
The error message:
error: environment variable `GIT_HASH` not defined
--> src/main.rs:10:25
|
10 | pub const GIT_HASH: &'static str = env!("GIT_HASH");
|
^^^^^^^^^^^^^^^^
Is there a way to pass such data at compile time? How can I communicate between the build script and the source code if not with environment variables? I can only think about writing data to some file, but I think this is overkill for this case.
I can only think about writing data to some file, but I think this is overkill for this case.
That's unfortunate, because that is the only way of doing it. Environment variables can't work because changes to the environment can't "leak" into other, non-child processes.
For simpler things, you can instruct Cargo to define conditional compilation flags, but those aren't powerful enough to communicate a string [1].
The details of generating code from a build script is detailed in the code generation section of the Cargo documentation.
[1]: I mean, unless you feel like breaking the hash into 160 config flags and then re-assembling them in the source being compiled, but that's even more overkill.