use std::path::Path;
use std::sync::OnceLock;
use serde::{Deserialize, Serialize};
pub const SHORT_HASH_LEN: usize = 12;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct BuildId {
#[serde(default)]
pub version: String,
#[serde(default)]
pub git: Option<String>,
#[serde(default)]
pub binary_sha256: Option<String>,
}
pub fn version_triple(version: &str) -> Option<(u64, u64, u64)> {
let core = version.trim().trim_start_matches('v');
let core = core.split(['-', '+']).next()?;
let mut it = core.split('.');
let major = it.next()?.parse().ok()?;
let minor = it.next().unwrap_or("0").parse().ok()?;
let patch = it.next().unwrap_or("0").parse().ok()?;
Some((major, minor, patch))
}
pub fn meets_minimum(peer: Option<&BuildId>, minimum: (u64, u64, u64)) -> bool {
peer.and_then(|b| version_triple(&b.version))
.map(|v| v >= minimum)
.unwrap_or(false)
}
impl BuildId {
pub fn short_hash(&self) -> Option<&str> {
let h = self.binary_sha256.as_deref()?;
let end = h
.char_indices()
.map(|(i, _)| i)
.nth(SHORT_HASH_LEN)
.unwrap_or(h.len());
Some(&h[..end])
}
pub fn label(&self) -> String {
let mut parts = Vec::new();
if !self.version.is_empty() {
parts.push(self.version.clone());
}
if let Some(g) = &self.git {
parts.push(format!("({})", g));
}
if let Some(h) = self.short_hash() {
parts.push(format!("sha:{}", h));
}
if parts.is_empty() {
"unknown".to_string()
} else {
parts.join(" ")
}
}
pub fn is_known(&self) -> bool {
!self.version.is_empty() || self.git.is_some() || self.binary_sha256.is_some()
}
pub fn same_build_as(&self, other: &BuildId) -> bool {
match (&self.binary_sha256, &other.binary_sha256) {
(Some(a), Some(b)) => a == b,
_ => self.version == other.version && self.git == other.git,
}
}
}
pub fn current() -> &'static BuildId {
static CURRENT: OnceLock<BuildId> = OnceLock::new();
CURRENT.get_or_init(|| BuildId {
version: env!("CARGO_PKG_VERSION").to_string(),
git: git_revision(),
binary_sha256: std::env::current_exe().ok().and_then(|p| hash_file(&p)),
})
}
fn git_revision() -> Option<String> {
let hash = option_env!("ZC_GIT_HASH")?;
Some(if option_env!("ZC_GIT_DIRTY") == Some("1") {
format!("{}-dirty", hash)
} else {
hash.to_string()
})
}
pub fn hash_file(path: &Path) -> Option<String> {
use std::io::Read;
let mut file = std::fs::File::open(path).ok()?;
let mut ctx = ring::digest::Context::new(&ring::digest::SHA256);
let mut buf = [0u8; 64 * 1024];
loop {
match file.read(&mut buf) {
Ok(0) => break,
Ok(n) => ctx.update(&buf[..n]),
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(_) => return None,
}
}
Some(hex::encode(ctx.finish().as_ref()))
}
#[cfg(test)]
mod version_gate_tests {
use super::*;
#[test]
fn versions_order_numerically_not_lexically() {
assert!(version_triple("0.0.34") > version_triple("0.0.9"));
assert!(version_triple("0.1.0") > version_triple("0.0.99"));
assert!(version_triple("1.0.0") > version_triple("0.9.9"));
assert_eq!(version_triple("0.0.34"), Some((0, 0, 34)));
}
#[test]
fn a_prerelease_or_v_prefix_orders_as_its_release() {
assert_eq!(version_triple("v0.0.34"), Some((0, 0, 34)));
assert_eq!(version_triple("0.0.34-rc1"), Some((0, 0, 34)));
assert_eq!(version_triple("0.0.34+build7"), Some((0, 0, 34)));
assert_eq!(version_triple("0.1"), Some((0, 1, 0)));
}
#[test]
fn nonsense_is_none_rather_than_a_guess() {
for bad in ["", "abc", "x.y.z", "..", "0.0.x"] {
assert_eq!(version_triple(bad), None, "{bad}");
}
}
#[test]
fn a_peer_that_discloses_nothing_does_not_meet_any_floor() {
assert!(!meets_minimum(None, (0, 0, 1)));
let silent = BuildId::default();
assert!(!meets_minimum(Some(&silent), (0, 0, 1)));
}
#[test]
fn a_peer_meets_a_floor_at_or_above_it() {
let peer = BuildId {
version: "0.0.34".into(),
git: None,
binary_sha256: None,
};
assert!(meets_minimum(Some(&peer), (0, 0, 34)), "equal passes");
assert!(meets_minimum(Some(&peer), (0, 0, 30)), "newer passes");
assert!(!meets_minimum(Some(&peer), (0, 0, 35)), "older is refused");
assert!(
!meets_minimum(Some(&peer), (0, 1, 0)),
"older minor refused"
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn current_reports_this_crate_and_a_64_hex_char_hash() {
let id = current();
assert_eq!(id.version, env!("CARGO_PKG_VERSION"));
let hash = id
.binary_sha256
.as_deref()
.expect("the test binary is readable, so it hashes");
assert_eq!(hash.len(), 64, "SHA-256 is 32 bytes = 64 hex chars");
assert!(hash
.chars()
.all(|c| c.is_ascii_hexdigit() && !c.is_uppercase()));
}
#[test]
fn current_is_computed_once_and_stable() {
assert_eq!(current(), current());
}
#[test]
fn hash_file_matches_a_known_sha256() {
let dir = std::env::temp_dir().join(format!("zc-build-id-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let empty = dir.join("empty");
std::fs::write(&empty, b"").unwrap();
assert_eq!(
hash_file(&empty).as_deref(),
Some("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
);
let abc = dir.join("abc");
std::fs::write(&abc, b"abc").unwrap();
assert_eq!(
hash_file(&abc).as_deref(),
Some("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn hash_file_is_none_for_a_path_that_is_not_there() {
assert_eq!(hash_file(Path::new("/nonexistent/zc-binary")), None);
}
#[test]
fn a_missing_build_block_deserializes_as_unknown() {
let none: Option<BuildId> = serde_json::from_str("null").unwrap();
assert!(none.is_none());
let partial: BuildId = serde_json::from_str(r#"{"version":"0.0.31"}"#).unwrap();
assert_eq!(partial.version, "0.0.31");
assert_eq!(partial.git, None);
assert_eq!(partial.binary_sha256, None);
assert!(partial.is_known());
assert!(!BuildId::default().is_known());
}
#[test]
fn the_hash_decides_when_both_sides_have_one() {
let a = BuildId {
version: "0.0.32".into(),
git: Some("0447049".into()),
binary_sha256: Some("aa".repeat(32)),
};
let cross_compiled = BuildId {
binary_sha256: Some("bb".repeat(32)),
..a.clone()
};
assert!(!a.same_build_as(&cross_compiled));
assert!(a.same_build_as(&a.clone()));
}
#[test]
fn without_a_hash_it_falls_back_to_version_and_commit() {
let hashless = BuildId {
version: "0.0.32".into(),
git: Some("0447049".into()),
binary_sha256: None,
};
let same_source = BuildId {
binary_sha256: Some("aa".repeat(32)),
..hashless.clone()
};
assert!(hashless.same_build_as(&same_source));
let older = BuildId {
version: "0.0.31".into(),
..hashless.clone()
};
assert!(!hashless.same_build_as(&older));
}
#[test]
fn label_drops_what_it_does_not_know() {
assert_eq!(
BuildId {
version: "0.0.32".into(),
git: Some("0447049-dirty".into()),
binary_sha256: Some("ab12cd34ef56".to_string() + &"0".repeat(52)),
}
.label(),
"0.0.32 (0447049-dirty) sha:ab12cd34ef56"
);
assert_eq!(
BuildId {
version: "0.0.32".into(),
git: None,
binary_sha256: None,
}
.label(),
"0.0.32"
);
assert_eq!(BuildId::default().label(), "unknown");
}
#[test]
fn short_hash_does_not_panic_on_a_stub_value() {
let stub = BuildId {
binary_sha256: Some("abc".into()),
..Default::default()
};
assert_eq!(stub.short_hash(), Some("abc"));
}
}