Skip to main content

calimero_primitives/
version.rs

1//! Version information and build metadata.
2//!
3//! Mirrors the approach used in [nearcore](https://github.com/near/nearcore):
4//! the `Version` struct lives in primitives; binaries set version env vars
5//! in their own build scripts and construct `Version` from those.
6//!
7//! **Intended use:**
8//! - **Protocol / network version exchange**: when sending or comparing version info
9//!   between nodes or in APIs (serialization via Serde/Borsh).
10//! - **Building version strings in binaries**: use [`Version::from_build_env`] with
11//!   `env!("...")` to construct a value for display or logging.
12
13use serde::{Deserialize, Serialize};
14
15/// Data structure for release version and build metadata (git describe, commit, rustc).
16///
17/// Used for protocol version exchange and for constructing version strings in
18/// binaries from build-time env vars (e.g. `MEROD_VERSION`, `MEROD_BUILD`).
19#[derive(Clone, Debug, Default, Serialize, Deserialize)]
20#[cfg_attr(
21    feature = "borsh",
22    derive(borsh::BorshSerialize, borsh::BorshDeserialize)
23)]
24pub struct Version {
25    /// Release version (e.g. from Cargo.toml or git tag).
26    pub version: String,
27    /// Build identifier (e.g. git describe).
28    pub build: String,
29    /// Git commit (short).
30    pub commit: String,
31    /// Rustc version used to build.
32    pub rustc_version: String,
33}
34
35impl Version {
36    /// Build from build-time env vars (e.g. in binaries that set `MEROD_*` / `MEROCTL_*`).
37    pub fn from_build_env(version: &str, build: &str, commit: &str, rustc_version: &str) -> Self {
38        Self {
39            version: version.to_string(),
40            build: build.to_string(),
41            commit: commit.to_string(),
42            rustc_version: rustc_version.to_string(),
43        }
44    }
45}
46
47impl std::fmt::Display for Version {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(
50            f,
51            "(release {}) (build {}) (commit {}) (rustc {})",
52            self.version, self.build, self.commit, self.rustc_version,
53        )
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::Version;
60
61    #[test]
62    fn from_build_env_sets_all_fields() {
63        let version = Version::from_build_env("1.2.3", "v1.2.3-5-gabc123", "abc123", "1.88.0");
64
65        assert_eq!(version.version, "1.2.3");
66        assert_eq!(version.build, "v1.2.3-5-gabc123");
67        assert_eq!(version.commit, "abc123");
68        assert_eq!(version.rustc_version, "1.88.0");
69    }
70
71    #[test]
72    fn display_uses_expected_format() {
73        let version = Version::from_build_env("1.2.3", "v1.2.3-5-gabc123", "abc123", "1.88.0");
74
75        assert_eq!(
76            version.to_string(),
77            "(release 1.2.3) (build v1.2.3-5-gabc123) (commit abc123) (rustc 1.88.0)"
78        );
79    }
80}