Skip to content

Commit 80f9670

Browse files
committed
refactor setting the git info to support more sources
1 parent 05066fe commit 80f9670

File tree

1 file changed

+35
-15
lines changed

1 file changed

+35
-15
lines changed

Diff for: build.rs

+35-15
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,15 @@ fn compress_man() {
4747
encoder.finish().unwrap();
4848
}
4949

50-
fn commit_info() {
51-
if !Path::new(".git").exists() {
52-
return;
53-
}
50+
struct CommitInfo {
51+
hash: String,
52+
short_hash: String,
53+
date: String,
54+
}
5455

55-
// Var set by bootstrap whenever omit-git-hash is enabled in rust-lang/rust's config.toml.
56-
println!("cargo:rerun-if-env-changed=CFG_OMIT_GIT_HASH");
57-
#[allow(clippy::disallowed_methods)]
58-
if std::env::var_os("CFG_OMIT_GIT_HASH").is_some() {
59-
return;
56+
fn commit_info_from_git() -> Option<CommitInfo> {
57+
if !Path::new(".git").exists() {
58+
return None;
6059
}
6160

6261
let output = match Command::new("git")
@@ -68,14 +67,35 @@ fn commit_info() {
6867
.output()
6968
{
7069
Ok(output) if output.status.success() => output,
71-
_ => return,
70+
_ => return None,
7271
};
72+
7373
let stdout = String::from_utf8(output.stdout).unwrap();
74-
let mut parts = stdout.split_whitespace();
75-
let mut next = || parts.next().unwrap();
76-
println!("cargo:rustc-env=CARGO_COMMIT_HASH={}", next());
77-
println!("cargo:rustc-env=CARGO_COMMIT_SHORT_HASH={}", next());
78-
println!("cargo:rustc-env=CARGO_COMMIT_DATE={}", next())
74+
let mut parts = stdout.split_whitespace().map(|s| s.to_string());
75+
76+
Some(CommitInfo {
77+
hash: parts.next()?,
78+
short_hash: parts.next()?,
79+
date: parts.next()?,
80+
})
81+
}
82+
83+
fn commit_info() {
84+
// Var set by bootstrap whenever omit-git-hash is enabled in rust-lang/rust's config.toml.
85+
println!("cargo:rerun-if-env-changed=CFG_OMIT_GIT_HASH");
86+
// ALLOWED: Accessing environment during build time shouldn't be prohibited.
87+
#[allow(clippy::disallowed_methods)]
88+
if std::env::var_os("CFG_OMIT_GIT_HASH").is_some() {
89+
return;
90+
}
91+
92+
let Some(git) = commit_info_from_git() else {
93+
return;
94+
};
95+
96+
println!("cargo:rustc-env=CARGO_COMMIT_HASH={}", git.hash);
97+
println!("cargo:rustc-env=CARGO_COMMIT_SHORT_HASH={}", git.short_hash);
98+
println!("cargo:rustc-env=CARGO_COMMIT_DATE={}", git.date);
7999
}
80100

81101
#[allow(clippy::disallowed_methods)]

0 commit comments

Comments
 (0)