about summary refs log tree commit diff
path: root/build.rs
blob: c987e4ad4f40a172ce4a18e3249cb4e19da9c982 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::process::Command;

// Embeds build provenance into the binary via env!() in src/lib.rs:
//
// - the git commit the binary was built from (short hash),
// - `-dirty` when that build had uncommitted changes, so a stamp is never
//   claim-able as a commit the code does not match,
// - a digest of the source files themselves, which distinguishes two
//   builds of the same commit (or of the same dirty tree) from each other,
// - the HEAD commit's date, not the wall-clock build time, so the build
//   stays a pure function of the source.
//
// Cargo only re-runs a build script when a file it declared changes, so
// `.git/HEAD` *and* the ref it points at are both declared below: without
// the ref, committing (which leaves `.git/HEAD` saying `ref: refs/heads/…`)
// would leave a stale hash stamped into the binary while the code moved on.

fn git(args: &[&str]) -> Option<String> {
    Command::new("git")
        .args(args)
        .output()
        .ok()
        .filter(|output| output.status.success())
        .and_then(|output| String::from_utf8(output.stdout).ok())
        .map(|s| s.trim().to_string())
}

/// `.git/HEAD` and, when it is a symbolic ref, the ref file itself, so a
/// commit re-runs this script.
fn watch_git_refs() {
    println!("cargo:rerun-if-changed=.git/HEAD");
    if let Ok(head) = std::fs::read_to_string(".git/HEAD") {
        if let Some(reference) = head.trim().strip_prefix("ref: ") {
            println!("cargo:rerun-if-changed=.git/{reference}");
        }
    }
    // Also the index: `git add` changes what a build's dirty flag means.
    println!("cargo:rerun-if-changed=.git/index");
}

/// A short digest over the source files git tracks, so two builds of the
/// same commit can be told apart when one of them was from a dirty tree.
fn source_digest() -> String {
    let Some(listing) = git(&["ls-files", "-z", "src", "build.rs", "Cargo.toml"]) else {
        return "unknown".to_string();
    };
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for path in listing.split('\0').filter(|path| !path.is_empty()) {
        for byte in path.as_bytes() {
            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
        }
        if let Ok(contents) = std::fs::read(path) {
            for byte in contents {
                hash = (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
            }
        }
    }
    format!("{hash:016x}")
}

fn main() {
    watch_git_refs();

    let dirty = git(&["status", "--porcelain", "--untracked-files=no"])
        .map(|status| !status.is_empty())
        .unwrap_or(false);
    let hash = git(&["rev-parse", "--short", "HEAD"]).unwrap_or_else(|| "unknown".to_string());
    let stamp = if dirty && hash != "unknown" {
        format!("{hash}-dirty")
    } else {
        hash
    };
    println!("cargo:rustc-env=GN4_GIT_HASH={stamp}");
    println!(
        "cargo:rustc-env=GN4_GIT_BRANCH={}",
        git(&["rev-parse", "--abbrev-ref", "HEAD"]).unwrap_or_else(|| "unknown".to_string())
    );
    println!("cargo:rustc-env=GN4_SOURCE_DIGEST={}", source_digest());

    let commit_date = git(&["show", "-s", "--format=%cd", "--date=format:%Y%m%d", "HEAD"])
        .unwrap_or_else(|| "unknown".to_string());
    println!("cargo:rustc-env=GN4_COMMIT_DATE={commit_date}");
}