tango-core 0.3.0

The tango schema, entities, migrations, and search contract
Documentation
//! Guards the promise that a released migration is never edited.
//!
//! A migration is recorded in `seaql_migrations` by name, and its SQL is never
//! read again by a database that applied it - so editing a released migration
//! changes what a *fresh* database replays to while every deployed database
//! keeps the old schema, with no error anywhere to say the two disagree.
//! `tango-core/migrations.lock` records the SHA-256 of every file at release
//! time; this test fails when one of those files changes or disappears.
//!
//! Migrations that are not in the lock are unreleased: they may still change,
//! and are locked by `scripts/lock-migrations.ps1 -Update`, which runs at tag
//! time. The lock is part of the release checklist in the README.
//!
//! CRLF is normalized to LF before hashing, at the byte level and identically
//! in the PowerShell script: the repository stores LF, the working tree on
//! Windows checks out CRLF, and the hash must not depend on which machine
//! runs the check.

use std::fs;
use std::path::{Path, PathBuf};

use sha2::{Digest, Sha256};

/// The bytes the lock hashes: the file content with every CRLF collapsed to
/// LF and nothing else changed.
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  ")
    );
}