Skip to main content

buildinfo/
lib.rs

1//! Git facts for `build.rs` scripts, with rerun triggers on the files they come from.
2
3use 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
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.
32pub 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
41/// Abbreviated or full hash of `HEAD`.
42pub fn commit_hash(short: bool) -> io::Result<String> {
43    git(&[
44        "rev-parse",
45        if short { "--short" } else { "--verify" },
46        "HEAD",
47    ])
48}
49
50/// Committer date of `HEAD` in RFC 3339.
51pub fn commit_date() -> io::Result<String> {
52    git(&["log", "-1", "--format=%cI", "HEAD"])
53}
54
55/// Prints `cargo:rerun-if-changed` for every file in [`head_files`].
56pub fn rerun_on_head_change() -> io::Result<()> {
57    for file in head_files()? {
58        println!("cargo:rerun-if-changed={file}");
59    }
60    Ok(())
61}