use aion_store::DeployedBinaryIdentity;
use crate::build_identity::BuildIdentity;
use sha2::{Digest, Sha256};
#[derive(Debug, thiserror::Error)]
pub enum BinaryIdentityCaptureError {
#[error("could not resolve the running server executable: {source}")]
CurrentExecutable {
#[source]
source: std::io::Error,
},
#[error("could not read running server executable `{path}`: {source}")]
ReadExecutable {
path: std::path::PathBuf,
#[source]
source: std::io::Error,
},
}
pub fn capture_binary_identity() -> Result<DeployedBinaryIdentity, BinaryIdentityCaptureError> {
let path = std::env::current_exe()
.map_err(|source| BinaryIdentityCaptureError::CurrentExecutable { source })?;
let bytes =
std::fs::read(&path).map_err(|source| BinaryIdentityCaptureError::ReadExecutable {
path: path.clone(),
source,
})?;
let identity = BuildIdentity::current();
let content_hash = lowercase_hex(&Sha256::digest(bytes));
Ok(DeployedBinaryIdentity {
version: identity.version.to_owned(),
commit: identity.commit.to_owned(),
dirty: identity.dirty.to_owned(),
content_hash,
})
}
#[must_use]
pub fn lowercase_hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut encoded = String::with_capacity(bytes.len().saturating_mul(2));
for byte in bytes {
encoded.push(char::from(DIGITS[usize::from(byte >> 4)]));
encoded.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
}
encoded
}