我在git存储库中托管了一个Rust项目,希望它在一些命令中能够打印版本号。我该如何将版本包含到程序中?我的想法是构建脚本可以设置环境变量,然后在编译项目时使用这些环境变量,但是这并不起作用:
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: environment variable `GIT_HASH` not defined
--> src/main.rs:10:25
|
10 | pub const GIT_HASH: &'static str = env!("GIT_HASH");
|
^^^^^^^^^^^^^^^^
有没有一种方法可以在编译时传递这样的数据?如果不能使用环境变量来进行构建脚本和源代码之间的通信,那该怎么办?我只能想到将数据写入某个文件,但我认为对于这种情况来说这太过繁琐了。
有没有办法在编译时传递数据?如果不能用环境变量来通信,如何在构建脚本和源代码之间进行通信?只能把数据写到文件中,但对于此案例来说似乎略显复杂。