use std::path::{Path, PathBuf};
use std::process::Command;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let repo_root = manifest_dir
.ancestors()
.find(|p| p.join(".git").exists())
.map(PathBuf::from);
let repo = repo_root.as_deref().unwrap_or(&manifest_dir);
let commit = git(repo, &["rev-parse", "HEAD"])
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "unknown".to_string());
println!("cargo:rustc-env=OSSCTL_GIT_COMMIT={commit}");
if let Some(head_path) = git_path(repo, "HEAD") {
println!("cargo:rerun-if-changed={head_path}");
}
if let Some(packed) = git_path(repo, "packed-refs") {
println!("cargo:rerun-if-changed={packed}");
}
if let Some(symref) = git(repo, &["symbolic-ref", "-q", "HEAD"]) {
if let Some(ref_path) = git_path(repo, &symref) {
println!("cargo:rerun-if-changed={ref_path}");
}
}
}
fn git(repo: &Path, args: &[&str]) -> Option<String> {
let out = Command::new("git")
.arg("-C")
.arg(repo)
.args(args)
.output()
.ok()?;
out.status
.success()
.then(|| String::from_utf8(out.stdout).ok())
.flatten()
.map(|s| s.trim().to_string())
}
fn git_path(repo: &Path, name: &str) -> Option<String> {
git(
repo,
&["rev-parse", "--path-format=absolute", "--git-path", name],
)
.filter(|s| !s.is_empty())
}