use std::path::Path;
use sha2::{Digest, Sha256};
use super::{Dependency, Error};
pub fn archive_digest(path: impl AsRef<Path>) -> Result<String, Error> {
let path = path.as_ref();
let io = |source| Error::Io {
path: path.to_owned(),
source,
};
let mut file = std::fs::File::open(path).map_err(io)?;
let mut hasher = Sha256::new();
std::io::copy(&mut file, &mut hasher).map_err(io)?;
Ok(hex(&hasher.finalize()))
}
#[must_use]
pub fn hash_dependencies(
requested: &[Option<Dependency>],
locked: &[Option<Dependency>],
) -> String {
let json = serde_json::to_string(&[nil_if_empty(requested), nil_if_empty(locked)])
.expect("dependencies serialise");
format!("sha256:{}", sha256(&go_escape(&json)))
}
#[must_use]
pub fn hash_dependencies_v2(requested: &[Option<Dependency>]) -> String {
let json =
serde_json::to_string(&serde_json::json!({ "dependencies": nil_if_empty(requested) }))
.expect("dependencies serialise");
format!("sha256:{}", sha256(&go_escape(&json)))
}
fn nil_if_empty(list: &[Option<Dependency>]) -> Option<&[Option<Dependency>]> {
(!list.is_empty()).then_some(list)
}
fn go_escape(json: &str) -> Vec<u8> {
json.replace('<', "\\u003c")
.replace('>', "\\u003e")
.replace('&', "\\u0026")
.replace('\u{2028}', "\\u2028")
.replace('\u{2029}', "\\u2029")
.into_bytes()
}
fn sha256(data: &[u8]) -> String {
hex(&Sha256::digest(data))
}
fn hex(bytes: &[u8]) -> String {
use std::fmt::Write;
bytes.iter().fold(String::new(), |mut out, b| {
write!(out, "{b:02x}").expect("writing to a string");
out
})
}
#[cfg(test)]
mod tests;