Skip to main content

khive_runtime/
build_info.rs

1//! Compile-time identity for the source and build that produced this runtime.
2
3#[cfg(test)]
4#[path = "build_info_support.rs"]
5mod build_info_support;
6
7/// Explicit source identity used when the build cannot inspect a Git checkout.
8pub const UNSTAMPED_REVISION: &str = "unstamped";
9
10/// Explicit build-time fallback used when no compile-time timestamp is available.
11pub const UNKNOWN_BUILD_TIME: &str = "unknown";
12
13/// Immutable provenance stamped into the binary at compile time.
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub struct BuildInfo {
16    pub source_revision: &'static str,
17    pub build_time: &'static str,
18}
19
20impl BuildInfo {
21    /// Construct build information while preserving an explicit unstamped state.
22    pub const fn new(
23        source_revision: Option<&'static str>,
24        build_time: Option<&'static str>,
25    ) -> Self {
26        Self {
27            source_revision: match source_revision {
28                Some(revision) => revision,
29                None => UNSTAMPED_REVISION,
30            },
31            build_time: match build_time {
32                Some(build_time) => build_time,
33                None => UNKNOWN_BUILD_TIME,
34            },
35        }
36    }
37
38    pub fn is_stamped(&self) -> bool {
39        self.source_revision != UNSTAMPED_REVISION
40    }
41}
42
43/// Provenance for the currently compiled runtime.
44pub const BUILD_INFO: BuildInfo = BuildInfo::new(
45    option_env!("KHIVE_SOURCE_REVISION"),
46    option_env!("KHIVE_BUILD_TIME"),
47);
48
49/// Rich version string used by `kkernel --version`.
50pub const BUILD_VERSION: &str = concat!(
51    env!("CARGO_PKG_VERSION"),
52    " (revision ",
53    env!("KHIVE_SOURCE_REVISION"),
54    ", built ",
55    env!("KHIVE_BUILD_TIME"),
56    ")"
57);
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use std::path::Path;
63    use std::process::Command;
64
65    #[test]
66    fn stamped_build_preserves_full_dirty_revision_and_time() {
67        let info = BuildInfo::new(
68            Some("45131c27b615f641c579046513d7c0ddd15c0bfb-dirty"),
69            Some("2026-07-31T20:00:00Z"),
70        );
71
72        assert_eq!(
73            info.source_revision,
74            "45131c27b615f641c579046513d7c0ddd15c0bfb-dirty"
75        );
76        assert_eq!(info.build_time, "2026-07-31T20:00:00Z");
77        assert!(info.is_stamped());
78    }
79
80    #[test]
81    fn unstamped_build_is_explicit() {
82        let info = BuildInfo::new(None, None);
83
84        assert_eq!(info.source_revision, UNSTAMPED_REVISION);
85        assert_eq!(info.build_time, UNKNOWN_BUILD_TIME);
86        assert!(!info.is_stamped());
87    }
88
89    #[test]
90    fn compiled_version_uses_the_compiled_provenance() {
91        assert!(BUILD_VERSION.contains(BUILD_INFO.source_revision));
92        assert!(BUILD_VERSION.contains(BUILD_INFO.build_time));
93
94        if BUILD_INFO.is_stamped() {
95            let revision = BUILD_INFO
96                .source_revision
97                .strip_suffix("-dirty")
98                .unwrap_or(BUILD_INFO.source_revision);
99            assert_eq!(revision.len(), 40);
100            assert!(revision.bytes().all(|byte| byte.is_ascii_hexdigit()));
101        }
102    }
103
104    #[test]
105    fn revision_derivation_distinguishes_clean_dirty_and_unstamped() {
106        let repo = tempfile::tempdir().unwrap();
107        run_git(repo.path(), &["init", "--quiet"]);
108        run_git(repo.path(), &["config", "user.email", "test@example.com"]);
109        run_git(repo.path(), &["config", "user.name", "khive test"]);
110        run_git(repo.path(), &["config", "commit.gpgsign", "false"]);
111        std::fs::write(repo.path().join("tracked.txt"), "clean\n").unwrap();
112        run_git(repo.path(), &["add", "tracked.txt"]);
113        run_git(repo.path(), &["commit", "--quiet", "-m", "baseline"]);
114
115        let revision = build_info_support::git_output(repo.path(), &["rev-parse", "HEAD"])
116            .expect("temp repository must have a revision");
117        assert_eq!(
118            build_info_support::source_revision(repo.path()).as_deref(),
119            Some(revision.as_str())
120        );
121
122        std::fs::write(repo.path().join("untracked.txt"), "not compiled\n").unwrap();
123        assert_eq!(
124            build_info_support::source_revision(repo.path()).as_deref(),
125            Some(revision.as_str())
126        );
127
128        std::fs::write(repo.path().join("tracked.txt"), "dirty\n").unwrap();
129        assert_eq!(
130            build_info_support::source_revision(repo.path()),
131            Some(format!("{revision}-dirty"))
132        );
133
134        let non_git = tempfile::tempdir().unwrap();
135        assert_eq!(build_info_support::source_revision(non_git.path()), None);
136    }
137
138    fn run_git(repo: &Path, args: &[&str]) {
139        let output = Command::new("git")
140            .env_remove("GIT_DIR")
141            .env_remove("GIT_WORK_TREE")
142            .arg("-C")
143            .arg(repo)
144            .args(args)
145            .output()
146            .expect("git must be available for build-provenance tests");
147        assert!(
148            output.status.success(),
149            "git {:?} failed: {}",
150            args,
151            String::from_utf8_lossy(&output.stderr)
152        );
153    }
154}