diff --git a/version/src/lib.rs b/version/src/lib.rs index b94683d89c..142266675b 100644 --- a/version/src/lib.rs +++ b/version/src/lib.rs @@ -11,14 +11,22 @@ pub struct Version { commit: Option, // first 4 bytes of the sha1 commit hash } +fn compute_commit(sha1: Option<&'static str>) -> Option { + let sha1 = sha1?; + if sha1.len() < 8 { + None + } else { + u32::from_str_radix(&sha1[..8], 16).ok() + } +} + impl Default for Version { fn default() -> Self { Self { major: env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap(), minor: env!("CARGO_PKG_VERSION_MINOR").parse().unwrap(), patch: env!("CARGO_PKG_VERSION_PATCH").parse().unwrap(), - commit: option_env!("CI_COMMIT") - .map(|sha1| u32::from_str_radix(&sha1[..8], 16).unwrap()), + commit: compute_commit(option_env!("CI_COMMIT")), } } } @@ -47,3 +55,16 @@ macro_rules! version { &*format!("{}", $crate::Version::default()) }; } + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_compute_commit() { + assert_eq!(compute_commit(None), None); + assert_eq!(compute_commit(Some("1234567890")), Some(0x12345678)); + assert_eq!(compute_commit(Some("HEAD")), None); + assert_eq!(compute_commit(Some("garbagein")), None); + } +}