1use std::io;
4use std::path::Path;
5use std::process::Command;
6
7#[cfg(test)]
8mod tests;
9
10fn git(args: &[&str]) -> io::Result<String> {
11 let output = Command::new("git").args(args).output()?;
12 if !output.status.success() {
13 return Err(io::Error::other(format!(
14 "git {} failed: {}",
15 args.join(" "),
16 String::from_utf8_lossy(&output.stderr).trim()
17 )));
18 }
19 String::from_utf8(output.stdout)
20 .map(|out| out.trim().to_owned())
21 .map_err(io::Error::other)
22}
23
24fn git_path(name: &str) -> io::Result<String> {
25 git(&["rev-parse", "--path-format=absolute", "--git-path", name])
26}
27
28pub fn head_files() -> io::Result<Vec<String>> {
33 let mut files = vec![git_path("HEAD")?, git_path("packed-refs")?];
34 if let Ok(branch) = git(&["symbolic-ref", "-q", "HEAD"]) {
35 files.push(git_path(&branch)?);
36 }
37 files.retain(|file| Path::new(file).exists());
38 Ok(files)
39}
40
41pub fn commit_hash(short: bool) -> io::Result<String> {
43 git(&[
44 "rev-parse",
45 if short { "--short" } else { "--verify" },
46 "HEAD",
47 ])
48}
49
50pub fn commit_date() -> io::Result<String> {
52 git(&["log", "-1", "--format=%cI", "HEAD"])
53}
54
55pub fn rerun_on_head_change() -> io::Result<()> {
57 for file in head_files()? {
58 println!("cargo:rerun-if-changed={file}");
59 }
60 Ok(())
61}