use serde::Serialize;
use serde_json::{Map, Value};
use crate::error::Error;
pub const LONG_VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
"\ncommit: ",
env!("GIT_COMMIT"),
"\nbuilt: ",
env!("BUILD_TIMESTAMP"),
"\nrustc: ",
env!("RUSTC_VERSION"),
"\ntarget: ",
env!("TARGET"),
);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Plain,
Json,
Toml,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BuildInfo {
pub version: String,
pub commit: String,
pub built: String,
pub rustc: String,
pub target: String,
pub gitversion: Map<String, Value>,
}
impl BuildInfo {
#[must_use]
pub fn current() -> Self {
Self::from_parts(
env!("CARGO_PKG_VERSION"),
env!("GIT_COMMIT"),
env!("BUILD_TIMESTAMP"),
env!("RUSTC_VERSION"),
env!("TARGET"),
env!("GITVERSION_JSON"),
)
}
#[must_use]
pub fn from_parts(
package_version: &str,
commit: &str,
built: &str,
rustc: &str,
target: &str,
stamp: &str,
) -> Self {
let gitversion = parse_stamp(stamp);
let version = gitversion
.get("SemVer")
.and_then(Value::as_str)
.unwrap_or(package_version)
.to_owned();
Self {
version,
commit: commit.to_owned(),
built: built.to_owned(),
rustc: rustc.to_owned(),
target: target.to_owned(),
gitversion,
}
}
#[must_use]
pub fn short(&self) -> String {
format!("v{}", self.version)
}
pub fn render(&self, format: Format, full: bool) -> Result<String, Error> {
if !full {
return Ok(match format {
Format::Plain => self.short(),
Format::Json => format!("{{\n \"version\": \"{}\"\n}}", self.short()),
Format::Toml => format!("version = \"{}\"", self.short()),
});
}
match format {
Format::Plain => Ok(self.plain()),
Format::Json => {
serde_json::to_string_pretty(self).map_err(|e| Error::Serde(e.to_string()))
}
Format::Toml => {
let mut sanitized = self.clone();
sanitized.gitversion.retain(|_, value| !value.is_null());
toml::to_string(&sanitized).map_err(|e| Error::Serde(e.to_string()))
}
}
}
fn plain(&self) -> String {
let mut out = format!(
"{}\ncommit: {}\nbuilt: {}\nrustc: {}\ntarget: {}",
self.short(),
self.commit,
self.built,
self.rustc,
self.target
);
if !self.gitversion.is_empty() {
let stamp: Vec<String> = self
.gitversion
.iter()
.map(|(key, value)| format!(" {key}: {}", scalar(value)))
.collect();
out.push_str("\ngitversion:\n");
out.push_str(&stamp.join("\n"));
}
out
}
}
fn parse_stamp(stamp: &str) -> Map<String, Value> {
let mut stamp: Map<String, Value> = serde_json::from_str(stamp).unwrap_or_default();
stamp.remove("AssemblySemVer");
stamp.remove("AssemblySemFileVer");
if let (Some(major), Some(minor)) = (stamp.get("Major"), stamp.get("Minor")) {
let combined = Value::from(format!("{major}.{minor}"));
stamp.insert("MajorMinor".to_owned(), combined);
}
stamp
}
fn scalar(value: &Value) -> String {
value
.as_str()
.map_or_else(|| value.to_string(), ToOwned::to_owned)
}
#[cfg(test)]
mod tests {
use super::*;
const STAMP: &str = r#"{"Major":0,"Minor":0,"Patch":1,"SemVer":"0.0.1-1",
"MajorMinorPatch":"0.0.1","BranchName":"main","BuildMetaData":null}"#;
fn info(stamp: &str) -> BuildInfo {
BuildInfo::from_parts(
"9.9.9",
"abc123-dirty",
"2026-07-29 00:00:00 UTC",
"rustc 1.97.1",
"x86_64-apple-darwin",
stamp,
)
}
#[test]
fn the_running_binarys_provenance_comes_from_the_build_script() {
let built = BuildInfo::current();
assert!(!built.commit.is_empty(), "no commit captured");
assert!(!built.target.is_empty(), "no target captured");
assert!(built.short().starts_with('v'), "got {}", built.short());
}
#[test]
fn the_short_form_prefixes_the_semver_from_the_stamp() {
assert_eq!(info(STAMP).short(), "v0.0.1-1");
}
#[test]
fn an_absent_stamp_falls_back_to_the_package_version() {
assert_eq!(info("{}").short(), "v9.9.9");
}
#[test]
fn a_malformed_stamp_is_treated_as_absent_rather_than_failing() {
assert_eq!(info("not json at all").short(), "v9.9.9");
}
#[test]
fn the_dotnet_assembly_versions_are_dropped() {
let built = info(
r#"{"Major":0,"Minor":0,"Patch":1,"SemVer":"0.0.1-1",
"AssemblySemVer":"0.0.1.0","AssemblySemFileVer":"0.0.1.0"}"#,
);
for dropped in ["AssemblySemVer", "AssemblySemFileVer"] {
assert!(
!built.gitversion.contains_key(dropped),
"{dropped} survived into the stamp"
);
}
assert_eq!(built.short(), "v0.0.1-1", "the version still comes through");
}
#[test]
fn major_minor_is_synthesized_the_way_the_mise_task_does() {
let built = info(STAMP);
assert_eq!(
built.gitversion.get("MajorMinor").and_then(Value::as_str),
Some("0.0")
);
}
#[test]
fn without_full_every_format_yields_only_the_short_line() {
for format in [Format::Plain, Format::Json, Format::Toml] {
let out = info(STAMP).render(format, false).unwrap();
assert!(out.contains("v0.0.1-1"), "{format:?}: {out}");
assert!(
!out.contains("rustc"),
"{format:?} leaked provenance: {out}"
);
}
}
#[test]
fn the_full_plain_form_names_every_provenance_field() {
let out = info(STAMP).render(Format::Plain, true).unwrap();
for expected in [
"v0.0.1-1",
"abc123-dirty",
"2026-07-29 00:00:00 UTC",
"rustc 1.97.1",
"x86_64-apple-darwin",
"BranchName",
] {
assert!(out.contains(expected), "missing {expected} in: {out}");
}
}
#[test]
fn the_full_plain_form_omits_the_stamp_section_when_there_is_no_stamp() {
let out = info("{}").render(Format::Plain, true).unwrap();
assert!(out.contains("v9.9.9"), "{out}");
assert!(!out.contains("gitversion:"), "empty heading shown: {out}");
}
#[test]
fn the_same_parts_always_describe_the_same_build() {
assert_eq!(info(STAMP), info(STAMP));
assert!(format!("{:?}", info(STAMP)).contains("BuildInfo"));
}
#[test]
fn the_full_json_form_keeps_the_stamp_types() {
let out = info(STAMP).render(Format::Json, true).unwrap();
let parsed: Value = serde_json::from_str(&out).unwrap();
assert_eq!(parsed["version"], Value::from("0.0.1-1"));
assert_eq!(parsed["gitversion"]["Major"], Value::from(0));
}
#[test]
fn the_full_toml_form_drops_entries_toml_cannot_represent() {
let out = info(STAMP).render(Format::Toml, true).unwrap();
assert!(out.contains("BranchName"), "{out}");
assert!(!out.contains("BuildMetaData"), "null survived: {out}");
}
}