use std::path::PathBuf;
use crate::{rerun_if_changed, run_command};
pub fn rebuild_if_branch_or_commit_changes() {
if let Ok(head_path) = git_path("HEAD") {
rerun_if_changed(&head_path); if let Ok(head) = std::fs::read_to_string(&head_path)
&& let Some(git_file) = head.strip_prefix("ref: ")
&& let Ok(path) = git_path(git_file)
{
if path.exists() {
rerun_if_changed(path); } else {
}
}
}
}
pub fn git_commit_hash() -> anyhow::Result<String> {
let git_hash = run_command("git", &["rev-parse", "HEAD"])?;
if git_hash.is_empty() {
anyhow::bail!("empty commit hash");
}
Ok(git_hash)
}
pub fn git_commit_short_hash() -> anyhow::Result<String> {
Ok(git_commit_hash()?[0..7].to_string())
}
fn parse_branch_from_github_ref() -> Option<String> {
let github_ref = std::env::var("GITHUB_REF").ok()?;
let branch = github_ref
.strip_prefix("refs/")?
.split_once('/')?
.1
.to_owned();
Some(branch)
}
pub fn git_branch() -> anyhow::Result<String> {
if let Some(branch) = parse_branch_from_github_ref() {
Ok(branch)
} else {
run_command("git", &["symbolic-ref", "--short", "HEAD"])
}
}
fn git_path(path: &str) -> anyhow::Result<PathBuf> {
let path = run_command("git", &["rev-parse", "--git-path", path])?;
Ok(path.into())
}