1
//! Git facts for `build.rs` scripts, with rerun triggers on the files they come from.
2

            
3
use std::io;
4
use std::path::Path;
5
use std::process::Command;
6

            
7
#[cfg(test)]
8
mod tests;
9

            
10
8
fn git(args: &[&str]) -> io::Result<String> {
11
8
    let output = Command::new("git").args(args).output()?;
12
8
    if !output.status.success() {
13
2
        return Err(io::Error::other(format!(
14
2
            "git {} failed: {}",
15
2
            args.join(" "),
16
2
            String::from_utf8_lossy(&output.stderr).trim()
17
2
        )));
18
6
    }
19
6
    String::from_utf8(output.stdout)
20
6
        .map(|out| out.trim().to_owned())
21
6
        .map_err(io::Error::other)
22
8
}
23

            
24
2
fn git_path(name: &str) -> io::Result<String> {
25
2
    git(&["rev-parse", "--path-format=absolute", "--git-path", name])
26
2
}
27

            
28
/// Paths that change whenever `HEAD` resolves to another commit: the `HEAD`
29
/// file, the branch ref it points to, and `packed-refs`. Resolved through git
30
/// so linked worktrees watch their own `HEAD` and the shared refs. Only
31
/// existing files: cargo reruns a script on every build for a missing one.
32
1
pub fn head_files() -> io::Result<Vec<String>> {
33
1
    let mut files = vec![git_path("HEAD")?, git_path("packed-refs")?];
34
1
    if let Ok(branch) = git(&["symbolic-ref", "-q", "HEAD"]) {
35
        files.push(git_path(&branch)?);
36
1
    }
37
2
    files.retain(|file| Path::new(file).exists());
38
1
    Ok(files)
39
1
}
40

            
41
/// Abbreviated or full hash of `HEAD`.
42
3
pub fn commit_hash(short: bool) -> io::Result<String> {
43
3
    git(&[
44
3
        "rev-parse",
45
3
        if short { "--short" } else { "--verify" },
46
3
        "HEAD",
47
    ])
48
3
}
49

            
50
/// Committer date of `HEAD` in RFC 3339.
51
1
pub fn commit_date() -> io::Result<String> {
52
1
    git(&["log", "-1", "--format=%cI", "HEAD"])
53
1
}
54

            
55
/// Prints `cargo:rerun-if-changed` for every file in [`head_files`].
56
pub fn rerun_on_head_change() -> io::Result<()> {
57
    for file in head_files()? {
58
        println!("cargo:rerun-if-changed={file}");
59
    }
60
    Ok(())
61
}