//! Content identity, independent of git history or build time. use sha2::{Digest, Sha256}; pub fn content_hash<'a>(files: impl IntoIterator) -> String { let mut files: Vec<_> = files.into_iter().collect(); files.sort_by(|a, b| a.0.cmp(b.0)); let mut hash = Sha256::new(); for (path, bytes) in files { hash.update((path.len() as u64).to_be_bytes()); hash.update(path.as_bytes()); hash.update((bytes.len() as u64).to_be_bytes()); hash.update(bytes); } format!("sha256:{:x}", hash.finalize()) } #[cfg(test)] mod tests { use super::*; /// RULE: The definitions revision is a pure function of definition paths and bytes in fixed order, so concurrent landings cannot share a revision for different content. #[test] fn revision_is_a_pure_function_of_definition_files() { let files = [ ("a.json", b"a".as_slice()), ("boards/b.json", b"b".as_slice()), ]; let original = content_hash(files); assert_eq!(original, content_hash(files.into_iter().rev())); assert_ne!( original, content_hash([("a.json", b"changed".as_slice()), files[1]]) ); assert_ne!(original, content_hash([files[0]])); assert_ne!( original, content_hash([files[0], ("themes/b.json", files[1].1)]) ); } }