build(cli): get build sha via git command

This commit is contained in:
ObserverOfTime 2024-10-24 20:14:08 +03:00 committed by Amaan Qureshi
parent 66cd81a4f8
commit 413b7cbcca

View file

@ -1,8 +1,7 @@
use std::{ use std::{
env, env,
ffi::OsStr,
fs,
path::{Path, PathBuf}, path::{Path, PathBuf},
process::Command,
time::SystemTime, time::SystemTime,
}; };
@ -62,81 +61,23 @@ fn web_playground_files_present() -> bool {
} }
fn read_git_sha() -> Option<String> { fn read_git_sha() -> Option<String> {
let mut repo_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let crate_path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut git_path; if !crate_path
loop { .parent()
git_path = repo_path.join(".git"); .map_or(false, |p| p.join(".git").is_dir())
if git_path.exists() { {
break;
}
if !repo_path.pop() {
return None;
}
}
let git_dir_path;
if git_path.is_dir() {
git_dir_path = git_path;
} else if let Ok(git_path_content) = fs::read_to_string(&git_path) {
git_dir_path = repo_path.join(git_path_content.get("gitdir: ".len()..).unwrap().trim_end());
} else {
return None; return None;
} }
let git_head_path = git_dir_path.join("HEAD");
if let Some(path) = git_head_path.to_str() {
println!("cargo:rerun-if-changed={path}");
}
if let Ok(mut head_content) = fs::read_to_string(&git_head_path) {
if head_content.ends_with('\n') {
head_content.pop();
}
// If we're on a branch, read the SHA from the ref file. Command::new("git")
if head_content.starts_with("ref: ") { .args(["rev-parse", "HEAD"])
head_content.replace_range(0.."ref: ".len(), ""); .current_dir(crate_path)
let ref_filename = { .output()
// Go to real non-worktree gitdir .map_or(None, |output| {
let git_dir_path = git_dir_path if !output.status.success() {
.parent() return None;
.and_then(|p| {
p.file_name()
.map(|n| n == OsStr::new("worktrees"))
.and_then(|x| x.then(|| p.parent()))
})
.flatten()
.unwrap_or(&git_dir_path);
let file = git_dir_path.join(&head_content);
if file.is_file() {
file
} else {
let packed_refs = git_dir_path.join("packed-refs");
if let Ok(packed_refs_content) = fs::read_to_string(&packed_refs) {
for line in packed_refs_content.lines() {
if let Some((hash, r#ref)) = line.split_once(' ') {
if r#ref == head_content {
if let Some(path) = packed_refs.to_str() {
println!("cargo:rerun-if-changed={path}");
}
return Some(hash.to_string());
}
}
}
}
return None;
}
};
if let Some(path) = ref_filename.to_str() {
println!("cargo:rerun-if-changed={path}");
} }
return fs::read_to_string(&ref_filename).ok(); Some(String::from_utf8_lossy(&output.stdout).to_string())
} })
// If we're on a detached commit, then the `HEAD` file itself contains the sha.
if head_content.len() == 40 {
return Some(head_content);
}
}
None
} }