Lines
84.21 %
Functions
87.5 %
Branches
100 %
//! Git facts for `build.rs` scripts, with rerun triggers on the files they come from.
use std::io;
use std::path::Path;
use std::process::Command;
#[cfg(test)]
mod tests;
fn git(args: &[&str]) -> io::Result<String> {
let output = Command::new("git").args(args).output()?;
if !output.status.success() {
return Err(io::Error::other(format!(
"git {} failed: {}",
args.join(" "),
String::from_utf8_lossy(&output.stderr).trim()
)));
}
String::from_utf8(output.stdout)
.map(|out| out.trim().to_owned())
.map_err(io::Error::other)
fn git_path(name: &str) -> io::Result<String> {
git(&["rev-parse", "--path-format=absolute", "--git-path", name])
/// Paths that change whenever `HEAD` resolves to another commit: the `HEAD`
/// file, the branch ref it points to, and `packed-refs`. Resolved through git
/// so linked worktrees watch their own `HEAD` and the shared refs. Only
/// existing files: cargo reruns a script on every build for a missing one.
pub fn head_files() -> io::Result<Vec<String>> {
let mut files = vec![git_path("HEAD")?, git_path("packed-refs")?];
if let Ok(branch) = git(&["symbolic-ref", "-q", "HEAD"]) {
files.push(git_path(&branch)?);
files.retain(|file| Path::new(file).exists());
Ok(files)
/// Abbreviated or full hash of `HEAD`.
pub fn commit_hash(short: bool) -> io::Result<String> {
git(&[
"rev-parse",
if short { "--short" } else { "--verify" },
"HEAD",
])
/// Committer date of `HEAD` in RFC 3339.
pub fn commit_date() -> io::Result<String> {
git(&["log", "-1", "--format=%cI", "HEAD"])
/// Prints `cargo:rerun-if-changed` for every file in [`head_files`].
pub fn rerun_on_head_change() -> io::Result<()> {
for file in head_files()? {
println!("cargo:rerun-if-changed={file}");
Ok(())