gitiverse-git 0.2.0

Git object store abstraction, packfile construction, strict quarantine ingest, canonical serialisation, and merge/diff helpers for gitiverse
Documentation
use std::path::Path;

use crate::store::{CliGitStore, GitError, GitStore, Oid, run_git_bytes, validate_ref_name};

/// Compare-and-swap reference update specification passed to [`quarantine_ingest`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefUpdateSpec {
    pub ref_name: String,
    pub expected_old_oid: Option<Oid>,
    pub new_oid: Option<Oid>,
}

/// Builds a thin delta packfile containing objects reachable from `wants` and not reachable from `haves`.
pub async fn build_pack(
    repo_dir: &Path,
    wants: &[Oid],
    haves: &[Oid],
) -> Result<Vec<u8>, GitError> {
    if wants.is_empty() {
        return Err(GitError::InvalidInput(
            "pack build requires at least one want OID".to_owned(),
        ));
    }

    let mut stdin_lines = String::new();
    for want in wants {
        stdin_lines.push_str(want.as_str());
        stdin_lines.push('\n');
    }
    for have in haves {
        stdin_lines.push('^');
        stdin_lines.push_str(have.as_str());
        stdin_lines.push('\n');
    }

    let output = run_git_bytes(
        repo_dir,
        &["pack-objects", "--revs", "--thin", "--stdout", "-q"],
        Some(stdin_lines.as_bytes()),
        &[],
    )
    .await?;

    if !output.status.success() {
        return Err(GitError::CommandFailed {
            command: "git pack-objects --revs --thin --stdout".to_owned(),
            status: output.status.code(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        });
    }

    Ok(output.stdout)
}

/// Ingests `pack_bytes` into an isolated quarantine object directory, runs strict `index-pack`, `fsck --strict`, and object connectivity checks before promoting objects and applying CAS ref updates atomically.
pub async fn quarantine_ingest(
    repo_dir: &Path,
    pack_bytes: &[u8],
    updates: &[RefUpdateSpec],
) -> Result<Vec<String>, GitError> {
    quarantine_ingest_inner(repo_dir, pack_bytes, updates, true).await
}

/// Strictly verifies `pack_bytes` inside an isolated quarantine object directory via `index-pack --strict` and promotes the resulting packfile without running repository-wide `fsck` (safe for freshly initialised `git clone` directories whose `HEAD` temporarily points to `refs/heads/.invalid`).
pub async fn quarantine_index_pack(repo_dir: &Path, pack_bytes: &[u8]) -> Result<(), GitError> {
    if pack_bytes.is_empty() {
        return Ok(());
    }
    let _ = quarantine_ingest_inner(repo_dir, pack_bytes, &[], false).await?;
    Ok(())
}

/// Ingests `pack_bytes` into an isolated quarantine object directory, runs strict `index-pack` (and `fsck --strict` when `run_repo_fsck` is true), and promotes verified packfiles into `objects/pack`.
async fn quarantine_ingest_inner(
    repo_dir: &Path,
    pack_bytes: &[u8],
    updates: &[RefUpdateSpec],
    run_repo_fsck: bool,
) -> Result<Vec<String>, GitError> {
    for update in updates {
        validate_ref_name(&update.ref_name)?;
    }

    let objects_dir = repo_dir.join("objects");
    let target_pack_dir = objects_dir.join("pack");
    tokio::fs::create_dir_all(&target_pack_dir).await?;

    let quarantine = tempfile::Builder::new()
        .prefix("quarantine-")
        .tempdir_in(&objects_dir)?;
    let quarantine_dir = quarantine.path();
    let quarantine_pack_dir = quarantine_dir.join("pack");
    tokio::fs::create_dir_all(&quarantine_pack_dir).await?;

    let env_vars = [
        ("GIT_OBJECT_DIRECTORY", quarantine_dir),
        ("GIT_ALTERNATE_OBJECT_DIRECTORIES", objects_dir.as_path()),
    ];

    if !pack_bytes.is_empty() {
        let index_out = run_git_bytes(
            repo_dir,
            &["index-pack", "--stdin", "--fix-thin", "--strict"],
            Some(pack_bytes),
            &env_vars,
        )
        .await?;
        if !index_out.status.success() {
            return Err(GitError::VerificationFailed(format!(
                "index-pack --strict failed: {}",
                String::from_utf8_lossy(&index_out.stderr).trim()
            )));
        }

        if run_repo_fsck {
            let fsck_out = run_git_bytes(
                repo_dir,
                &["fsck", "--strict", "--no-dangling"],
                None,
                &env_vars,
            )
            .await?;
            if !fsck_out.status.success() {
                return Err(GitError::VerificationFailed(format!(
                    "fsck --strict failed: {}",
                    String::from_utf8_lossy(&fsck_out.stderr).trim()
                )));
            }
        }
    }

    // Verify full object graph connectivity for every proposed non-delete target before promoting.
    let new_oids: Vec<&str> = updates
        .iter()
        .filter_map(|u| u.new_oid.as_ref().map(Oid::as_str))
        .collect();
    if !new_oids.is_empty() {
        let mut args = vec!["rev-list", "--objects"];
        args.extend(new_oids);
        args.push("--not");
        args.push("--all");
        let conn_out = run_git_bytes(repo_dir, &args, None, &env_vars).await?;
        if !conn_out.status.success() {
            return Err(GitError::VerificationFailed(format!(
                "connectivity check failed: {}",
                String::from_utf8_lossy(&conn_out.stderr).trim()
            )));
        }
    }

    // Check compare-and-swap preconditions before promoting any objects out of quarantine.
    let store = CliGitStore::new(repo_dir);
    for update in updates {
        let current = store.resolve_ref(&update.ref_name).await?;
        match (&current, &update.expected_old_oid) {
            (Some(curr), Some(expected)) if curr == expected => {}
            (None, None) => {}
            (curr, expected) => {
                return Err(GitError::CasConflict {
                    ref_name: update.ref_name.clone(),
                    details: format!("expected {expected:?}, found {curr:?}"),
                });
            }
        }
    }

    // Promote verified pack and index files from quarantine into objects/pack.
    if !pack_bytes.is_empty() {
        let mut entries = tokio::fs::read_dir(&quarantine_pack_dir).await?;
        let mut files = Vec::new();
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if let Some(name) = path.file_name().and_then(|n| n.to_str())
                && (name.ends_with(".pack") || name.ends_with(".idx"))
            {
                let dst = target_pack_dir.join(name);
                files.push((path, dst));
            }
        }
        // Promote `.pack` files before `.idx` files so Git never observes a dangling index.
        files.sort_by_key(|(src, _)| src.extension().and_then(|e| e.to_str()) == Some("idx"));
        for (src, dst) in files {
            tokio::fs::rename(src, dst).await?;
        }
    }

    if !updates.is_empty() {
        let mut batch = String::new();
        for update in updates {
            match (&update.new_oid, &update.expected_old_oid) {
                (Some(new_oid), Some(old_oid)) => {
                    batch.push_str(&format!(
                        "update {} {} {}\n",
                        update.ref_name,
                        new_oid.as_str(),
                        old_oid.as_str()
                    ));
                }
                (Some(new_oid), None) => {
                    batch.push_str(&format!(
                        "create {} {}\n",
                        update.ref_name,
                        new_oid.as_str()
                    ));
                }
                (None, Some(old_oid)) => {
                    batch.push_str(&format!(
                        "delete {} {}\n",
                        update.ref_name,
                        old_oid.as_str()
                    ));
                }
                (None, None) => {
                    batch.push_str(&format!("delete {}\n", update.ref_name));
                }
            }
        }

        let ref_out = run_git_bytes(
            repo_dir,
            &["update-ref", "--stdin"],
            Some(batch.as_bytes()),
            &[],
        )
        .await?;
        if !ref_out.status.success() {
            let stderr = String::from_utf8_lossy(&ref_out.stderr).into_owned();
            if stderr.contains("cannot lock ref")
                || stderr.contains("is at")
                || stderr.contains("expected")
                || stderr.contains("already exists")
            {
                return Err(GitError::CasConflict {
                    ref_name: updates
                        .iter()
                        .map(|u| u.ref_name.as_str())
                        .collect::<Vec<_>>()
                        .join(", "),
                    details: stderr.trim().to_owned(),
                });
            }
            return Err(GitError::CommandFailed {
                command: "git update-ref --stdin".to_owned(),
                status: ref_out.status.code(),
                stderr,
            });
        }
    }

    Ok(updates.iter().map(|u| u.ref_name.clone()).collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::test_helpers::create_commit_in_bare;

    #[tokio::test]
    async fn thin_pack_build_and_quarantine_ingest_round_trip() {
        let src_dir = tempfile::tempdir().unwrap();
        let dst_dir = tempfile::tempdir().unwrap();
        let src = CliGitStore::init_bare_at(src_dir.path()).await.unwrap();
        let dst = CliGitStore::init_bare_at(dst_dir.path()).await.unwrap();

        let c1 = create_commit_in_bare(
            src_dir.path(),
            "refs/heads/main",
            &[],
            &[("a.txt", b"first version\n")],
            "c1",
        )
        .await;

        let full_pack = build_pack(src_dir.path(), std::slice::from_ref(&c1), &[])
            .await
            .unwrap();
        quarantine_ingest(
            dst_dir.path(),
            &full_pack,
            &[RefUpdateSpec {
                ref_name: "refs/heads/main".to_owned(),
                expected_old_oid: None,
                new_oid: Some(c1.clone()),
            }],
        )
        .await
        .unwrap();
        assert_eq!(
            dst.resolve_ref("refs/heads/main").await.unwrap(),
            Some(c1.clone())
        );

        // Now create a second commit in src and build a thin delta pack against c1.
        let c2 = create_commit_in_bare(
            src_dir.path(),
            "refs/heads/main",
            &[&c1],
            &[("a.txt", b"first version\nsecond line\n")],
            "c2",
        )
        .await;
        let thin_pack = build_pack(
            src_dir.path(),
            std::slice::from_ref(&c2),
            std::slice::from_ref(&c1),
        )
        .await
        .unwrap();

        quarantine_ingest(
            dst_dir.path(),
            &thin_pack,
            &[RefUpdateSpec {
                ref_name: "refs/heads/main".to_owned(),
                expected_old_oid: Some(c1.clone()),
                new_oid: Some(c2.clone()),
            }],
        )
        .await
        .unwrap();
        assert_eq!(dst.resolve_ref("refs/heads/main").await.unwrap(), Some(c2));
        assert!(src.object_exists(&c1).await.unwrap());
    }

    #[tokio::test]
    async fn corrupt_pack_and_missing_parent_are_rejected_without_mutating_dst() {
        let src_dir = tempfile::tempdir().unwrap();
        let dst_dir = tempfile::tempdir().unwrap();
        CliGitStore::init_bare_at(src_dir.path()).await.unwrap();
        let dst = CliGitStore::init_bare_at(dst_dir.path()).await.unwrap();

        let fake_oid = Oid::parse(&"1".repeat(40)).unwrap();
        let err = quarantine_ingest(
            dst_dir.path(),
            b"not a valid git packfile",
            &[RefUpdateSpec {
                ref_name: "refs/heads/main".to_owned(),
                expected_old_oid: None,
                new_oid: Some(fake_oid),
            }],
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, GitError::VerificationFailed(_)),
            "got {err:?}"
        );
        assert_eq!(dst.resolve_ref("refs/heads/main").await.unwrap(), None);

        // Missing parent commit (thin pack built against c1 pushed into empty dst without c1).
        let c1 = create_commit_in_bare(
            src_dir.path(),
            "refs/heads/main",
            &[],
            &[("a.txt", b"hello\n")],
            "c1",
        )
        .await;
        let c2 = create_commit_in_bare(
            src_dir.path(),
            "refs/heads/main",
            &[&c1],
            &[("a.txt", b"hello world\n")],
            "c2",
        )
        .await;
        let thin_only = build_pack(
            src_dir.path(),
            std::slice::from_ref(&c2),
            std::slice::from_ref(&c1),
        )
        .await
        .unwrap();
        let err_missing = quarantine_ingest(
            dst_dir.path(),
            &thin_only,
            &[RefUpdateSpec {
                ref_name: "refs/heads/main".to_owned(),
                expected_old_oid: None,
                new_oid: Some(c2.clone()),
            }],
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err_missing, GitError::VerificationFailed(_)),
            "got {err_missing:?}"
        );
        // Quarantined c2 must NOT have leaked into dst's object database.
        assert!(!dst.object_exists(&c2).await.unwrap());
        assert_eq!(dst.resolve_ref("refs/heads/main").await.unwrap(), None);
    }
}