From 1c85d62fe48196b149b5a878f75dfedf86ea65ed Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Mon, 11 May 2020 22:53:48 -0700 Subject: [PATCH] Fix crash when CI_COMMIT=HEAD (#9994) (#9998) automerge (cherry picked from commit 28d1f7c5e77492ad2ac7fb1cd4b7afe141479282) Co-authored-by: Michael Vines --- version/src/lib.rs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) 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); + } +}