use std::{
fmt,
path::{Path, PathBuf},
str::FromStr,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
const TREE_DOMAIN: &[u8] = b"markupwright:workspace:v1\0";
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct Checksum([u8; 32]);
#[derive(Clone, Copy, Debug)]
pub(crate) struct FileChecksum {
length: usize,
checksum: Checksum,
}
impl FileChecksum {
#[must_use]
pub(crate) const fn checksum(self) -> Checksum {
self.checksum
}
}
impl fmt::Debug for Checksum {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_tuple("Checksum")
.field(&self.to_string())
.finish()
}
}
impl fmt::Display for Checksum {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", blake3::Hash::from_bytes(self.0).to_hex())
}
}
impl FromStr for Checksum {
type Err = blake3::HexError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let hash = blake3::Hash::from_hex(value)?;
Ok(Self(*hash.as_bytes()))
}
}
impl Serialize for Checksum {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for Checksum {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
value.parse().map_err(D::Error::custom)
}
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum Error {
#[error("failed to checksum {}: {source}", path.display())]
Read {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("checksum path {} is outside the repository: {source}", path.display())]
Outside {
path: PathBuf,
#[source]
source: std::path::StripPrefixError,
},
#[error("checksum path {} is not portable UTF-8", path.display())]
NotPortable { path: PathBuf },
#[error("checksum input is too large: {source}")]
TooLarge {
#[source]
source: std::num::TryFromIntError,
},
}
#[must_use]
pub(crate) fn bytes(contents: impl AsRef<[u8]>) -> Checksum {
Checksum(*blake3::hash(contents.as_ref()).as_bytes())
}
#[must_use]
pub(crate) fn contents(contents: impl AsRef<[u8]>) -> FileChecksum {
let contents = contents.as_ref();
FileChecksum {
length: contents.len(),
checksum: bytes(contents),
}
}
pub(crate) fn file(path: &Path) -> Result<Checksum, Error> {
let contents = std::fs::read(path).map_err(|source| Error::Read {
path: path.to_path_buf(),
source,
})?;
Ok(bytes(contents))
}
pub(crate) fn executable() -> Result<Checksum, Error> {
let path = std::env::current_exe().map_err(|source| Error::Read {
path: PathBuf::from("current executable"),
source,
})?;
file(&path)
}
#[cfg(test)]
pub(crate) fn tree(root: &Path, paths: &[PathBuf]) -> Result<Checksum, Error> {
let entries = paths
.iter()
.map(|path| {
let bytes = std::fs::read(path).map_err(|source| Error::Read {
path: path.clone(),
source,
})?;
Ok((path.clone(), contents(bytes)))
})
.collect::<Result<Vec<_>, Error>>()?;
tree_entries(root, &entries)
}
pub(crate) fn tree_entries(
root: &Path,
entries: &[(PathBuf, FileChecksum)],
) -> Result<Checksum, Error> {
let mut entries = entries.iter().collect::<Vec<_>>();
entries.sort_by(|left, right| left.0.cmp(&right.0));
let mut hasher = blake3::Hasher::new();
hasher.update(TREE_DOMAIN);
update_length(&mut hasher, entries.len())?;
for (path, file) in entries {
let relative = path.strip_prefix(root).map_err(|source| Error::Outside {
path: path.clone(),
source,
})?;
let relative = relative
.to_str()
.ok_or_else(|| Error::NotPortable { path: path.clone() })?
.replace('\\', "/");
update_length(&mut hasher, relative.len())?;
hasher.update(relative.as_bytes());
update_length(&mut hasher, file.length)?;
hasher.update(file.checksum.0.as_slice());
}
Ok(Checksum(*hasher.finalize().as_bytes()))
}
pub(crate) fn tree_map(
root: &Path,
entries: &std::collections::BTreeMap<PathBuf, FileChecksum>,
) -> Result<Checksum, Error> {
let entries = entries
.iter()
.map(|(path, checksum)| (path.clone(), *checksum))
.collect::<Vec<_>>();
tree_entries(root, &entries)
}
fn update_length(hasher: &mut blake3::Hasher, length: usize) -> Result<(), Error> {
let length = u64::try_from(length).map_err(|source| Error::TooLarge { source })?;
hasher.update(&length.to_le_bytes());
Ok(())
}
#[cfg(test)]
mod tests {
use googletest::prelude::*;
use super::*;
#[gtest]
fn tree_checksum_tracks_paths_and_contents() -> Result<()> {
let directory = tempfile::tempdir().or_fail()?;
let first = directory.path().join("a.txt");
let second = directory.path().join("b.txt");
std::fs::write(&first, "same").or_fail()?;
std::fs::write(&second, "same").or_fail()?;
let one = tree(directory.path(), std::slice::from_ref(&first)).or_fail()?;
let two = tree(directory.path(), &[first.clone(), second.clone()]).or_fail()?;
verify_that!(one, not(eq(two)))?;
std::fs::write(&first, "changed").or_fail()?;
verify_that!(
tree(directory.path(), &[first, second]).or_fail()?,
not(eq(two))
)
}
#[gtest]
fn loaded_checksums_describe_the_bytes_that_were_read() -> Result<()> {
let directory = tempfile::tempdir().or_fail()?;
let path = directory.path().join("input.md.in");
std::fs::write(&path, "before").or_fail()?;
let entries = vec![(path.clone(), contents("before"))];
let loaded = tree_entries(directory.path(), &entries).or_fail()?;
std::fs::write(&path, "after").or_fail()?;
let current = tree(directory.path(), &[path]).or_fail()?;
verify_that!(loaded, not(eq(current)))
}
}