I host a Rust project in a git repository and I want it to print a version for some command. How to include the version in the program? I thought that the build script could set environment variables that could be used when 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);
}
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 any way to pass such data at compile time? How can I communicate between script assembly and source code, if not environment variables? I can only think of writing data to some file, but I think this is too much for this case.
source
share