use std::path::Path;
use ckg_core::Result;
pub fn head_sha(path: &Path) -> Result<String> {
match git2::Repository::open(path) {
Ok(repo) => {
if let Some(workdir) = repo.workdir() {
let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let canonical_workdir = workdir.canonicalize().unwrap_or_else(|_| workdir.to_path_buf());
if canonical_path != canonical_workdir {
tracing::debug!(
"head_sha: {path} opened repo with different workdir {workdir}; skipping",
path = path.display(),
workdir = workdir.display(),
);
return Ok(String::new());
}
}
match repo.head().and_then(|h| h.peel_to_commit()) {
Ok(commit) => Ok(commit.id().to_string()),
Err(e) => {
tracing::debug!(
"head_sha: repo at {} has no peelable HEAD: {e}",
path.display()
);
Ok(String::new())
}
}
}
Err(e) => {
tracing::debug!("head_sha: not a git repo at {}: {e}", path.display());
Ok(String::new())
}
}
}