use std::fs;
use std::path::{Path, PathBuf};
use sha2::{Digest, Sha256};
fn normalized(path: &Path) -> Vec<u8> {
let bytes = fs::read(path).unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'\r' && bytes.get(i + 1) == Some(&b'\n') {
out.push(b'\n');
i += 2;
} else {
out.push(bytes[i]);
i += 1;
}
}
out
}
fn sha256_hex(path: &Path) -> String {
let mut hasher = Sha256::new();
hasher.update(normalized(path));
format!("{:x}", hasher.finalize())
}
#[test]
fn released_migrations_are_unchanged() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let lock_path = root.join("migrations.lock");
let lock = fs::read_to_string(&lock_path)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", lock_path.display()));
let mut checked = 0usize;
let mut failures = Vec::new();
for (index, line) in lock.lines().enumerate() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let mut parts = line.split_whitespace();
let (Some(hash), Some(name)) = (parts.next(), parts.next()) else {
failures.push(format!("line {}: expected `<sha256> <file>`", index + 1));
continue;
};
let path = root.join("src/migration/sql").join(name);
if !path.is_file() {
failures.push(format!("{name}: locked, but no longer in sql/"));
continue;
}
let actual = sha256_hex(&path);
if actual != hash {
failures.push(format!(
"{name}: changed since release\n locked {hash}\n actual {actual}"
));
}
checked += 1;
}
assert!(checked > 0, "{} has no entries", lock_path.display());
assert!(
failures.is_empty(),
"released migrations must not be edited - add a new migration instead; \
regenerate the lock at tag time with `scripts/lock-migrations.ps1 -Update`:\n {}",
failures.join("\n ")
);
}