use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const PKG_NAME: &str = env!("CARGO_PKG_NAME");
pub const GIT_HASH: &str = env!("GIT_COMMIT_HASH");
pub const COMMIT_DATE: &str = env!("GIT_COMMIT_DATE");
pub const LONG_VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GIT_COMMIT_HASH"),
" ",
env!("GIT_COMMIT_DATE"),
")"
);
pub fn version_string() -> String {
format!("{PKG_NAME} v{VERSION} ({GIT_HASH})")
}
pub fn provenance_json() -> serde_json::Value {
serde_json::json!({
"version": VERSION,
"commit": GIT_HASH,
"commit_date": COMMIT_DATE,
})
}
#[derive(Debug, Serialize, Deserialize)]
struct PersistedBuild {
build: u64,
started_at: String,
}
#[derive(Debug, Clone)]
pub struct BuildInfo {
pub version: &'static str,
pub build: u64,
#[allow(dead_code)]
pub started_at: String,
}
impl BuildInfo {
pub async fn load_and_increment(state_dir: &Path) -> Result<Self> {
tokio::fs::create_dir_all(state_dir).await?;
Self::load_and_increment_in(state_dir).await
}
pub async fn load_and_increment_in(dir: &Path) -> Result<Self> {
tokio::fs::create_dir_all(dir)
.await
.with_context(|| format!("failed to create {}", dir.display()))?;
let file = dir.join("build.json");
let previous = read_previous(&file).await;
let next = previous.saturating_add(1);
let started_at = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
let persisted = PersistedBuild {
build: next,
started_at: started_at.clone(),
};
write_atomic(dir, &file, &persisted).await?;
Ok(Self {
version: env!("CARGO_PKG_VERSION"),
build: next,
started_at,
})
}
pub fn display_string(&self) -> String {
format!("{PKG_NAME} v{} build #{}", self.version, self.build)
}
}
async fn read_previous(file: &Path) -> u64 {
match tokio::fs::read(file).await {
Ok(bytes) => match serde_json::from_slice::<PersistedBuild>(&bytes) {
Ok(p) => p.build,
Err(_) => 0,
},
Err(_) => 0,
}
}
async fn write_atomic(dir: &Path, file: &Path, payload: &PersistedBuild) -> Result<()> {
let tmp: PathBuf = dir.join("build.json.tmp");
let bytes = serde_json::to_vec_pretty(payload).context("serialize build.json")?;
tokio::fs::write(&tmp, &bytes)
.await
.with_context(|| format!("failed to write {}", tmp.display()))?;
tokio::fs::rename(&tmp, file)
.await
.with_context(|| format!("failed to rename {} -> {}", tmp.display(), file.display()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn starts_at_one_when_missing() {
let dir = tempfile::tempdir().unwrap();
let info = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
assert_eq!(info.build, 1);
assert_eq!(info.version, env!("CARGO_PKG_VERSION"));
assert!(info.started_at.ends_with('Z'));
let bytes = tokio::fs::read(dir.path().join("build.json"))
.await
.unwrap();
let p: PersistedBuild = serde_json::from_slice(&bytes).unwrap();
assert_eq!(p.build, 1);
}
#[tokio::test]
async fn increments_across_calls() {
let dir = tempfile::tempdir().unwrap();
let a = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
let b = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
let c = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
assert_eq!(a.build, 1);
assert_eq!(b.build, 2);
assert_eq!(c.build, 3);
}
#[tokio::test]
async fn corrupt_file_resets_to_one() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::create_dir_all(dir.path()).await.unwrap();
tokio::fs::write(dir.path().join("build.json"), b"not json at all")
.await
.unwrap();
let info = BuildInfo::load_and_increment_in(dir.path()).await.unwrap();
assert_eq!(info.build, 1, "corrupt file should be treated as build=0");
}
#[tokio::test]
async fn display_string_format() {
let info = BuildInfo {
version: "0.1.0",
build: 42,
started_at: "2026-04-22T17:31:30Z".to_string(),
};
let s = info.display_string();
assert!(s.contains("v0.1.0"), "got: {s}");
assert!(s.contains("build #42"), "got: {s}");
}
#[test]
fn version_string_contains_version() {
let s = version_string();
assert!(s.contains("v"));
assert!(s.contains(VERSION));
assert!(s.contains(GIT_HASH));
}
#[test]
fn provenance_constants_are_well_formed() {
assert!(!GIT_HASH.is_empty(), "GIT_HASH must never be empty");
assert!(!COMMIT_DATE.is_empty(), "COMMIT_DATE must never be empty");
if GIT_HASH != "unknown" {
assert!(
GIT_HASH.len() >= 7 && GIT_HASH.chars().all(|c| c.is_ascii_hexdigit()),
"expected a short hex SHA or \"unknown\", got: {GIT_HASH}"
);
}
if COMMIT_DATE != "unknown" {
let parts: Vec<&str> = COMMIT_DATE.split('-').collect();
assert!(
parts.len() == 3 && parts.iter().all(|p| p.chars().all(|c| c.is_ascii_digit())),
"expected YYYY-MM-DD or \"unknown\", got: {COMMIT_DATE}"
);
}
}
#[test]
fn long_version_carries_semver_and_provenance() {
assert_eq!(
LONG_VERSION,
format!("{VERSION} ({GIT_HASH} {COMMIT_DATE})")
);
assert!(LONG_VERSION.starts_with(VERSION));
assert!(LONG_VERSION.contains(GIT_HASH));
}
#[test]
fn provenance_json_carries_version_and_commit() {
let v = provenance_json();
assert_eq!(v["version"], VERSION);
assert_eq!(v["commit"], GIT_HASH);
assert_eq!(v["commit_date"], COMMIT_DATE);
assert!(v["commit"].is_string(), "commit must be a string, not null");
}
#[test]
fn git_probe_fails_outside_a_checkout_so_fallback_engages() {
let dir = tempfile::tempdir().unwrap();
let output = std::process::Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.current_dir(dir.path())
.env("GIT_CEILING_DIRECTORIES", dir.path())
.env("GIT_DIR", dir.path().join("definitely-not-a-git-dir"))
.output();
if let Ok(o) = output {
assert!(
!o.status.success(),
"git must not resolve a SHA outside a checkout; got: {}",
String::from_utf8_lossy(&o.stdout)
);
}
}
#[test]
fn packed_branch_ref_leaves_only_the_reflog_witnessing_a_commit() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let run = |args: &[&str]| {
let out = std::process::Command::new("git")
.args(args)
.current_dir(root)
.env("GIT_AUTHOR_NAME", "t")
.env("GIT_AUTHOR_EMAIL", "t@t")
.env("GIT_COMMITTER_NAME", "t")
.env("GIT_COMMITTER_EMAIL", "t@t")
.output()
.expect("run git");
assert!(out.status.success(), "git {args:?} failed");
String::from_utf8_lossy(&out.stdout).trim().to_string()
};
if std::process::Command::new("git")
.arg("--version")
.output()
.is_err()
{
return;
}
run(&["init", "-q", "-b", "main", "."]);
std::fs::write(root.join("f"), "a").unwrap();
run(&["add", "-A"]);
run(&["commit", "-q", "-m", "one"]);
run(&["pack-refs", "--all"]);
let git_path = |spec: &str| root.join(run(&["rev-parse", "--git-path", spec]));
let loose = git_path("refs/heads/main");
let head = git_path("HEAD");
let reflog = git_path("logs/HEAD");
assert!(
!loose.exists(),
"expected the branch ref to be packed away; if git stopped packing \
here the premise for watching logs/HEAD needs rechecking"
);
assert!(reflog.exists(), "reflog must exist to be watchable");
let head_before = std::fs::read_to_string(&head).unwrap();
let reflog_before = std::fs::read_to_string(&reflog).unwrap();
std::fs::write(root.join("f"), "b").unwrap();
run(&["add", "-A"]);
run(&["commit", "-q", "-m", "two"]);
assert_eq!(
head_before,
std::fs::read_to_string(&head).unwrap(),
"HEAD still just says `ref: refs/heads/main` — watching it alone \
cannot catch a commit on a packed branch"
);
assert_ne!(
reflog_before,
std::fs::read_to_string(&reflog).unwrap(),
"the reflog must record the new commit — this is what makes \
logs/HEAD a sufficient watch when the ref is packed"
);
}
#[tokio::test]
async fn creates_missing_parent_dir() {
let root = tempfile::tempdir().unwrap();
let nested = root.path().join("deep").join(".state");
assert!(!nested.exists());
let info = BuildInfo::load_and_increment_in(&nested).await.unwrap();
assert_eq!(info.build, 1);
assert!(nested.join("build.json").exists());
}
}