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 fn version_string() -> String {
format!("{PKG_NAME} v{VERSION} ({GIT_HASH})")
}
#[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));
}
#[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());
}
}