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::collections::BTreeSet;
use std::path::Path;

use crate::store::{GitError, Oid, run_git_bytes};

/// Outcome of a 3-way mergeability check (`git merge-tree --write-tree`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MergeCheckResult {
    Clean { tree_oid: Oid },
    Conflicts { files: Vec<String>, details: String },
}

/// Per-file diff line count statistics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiffFileStat {
    pub path: String,
    pub additions: Option<u64>,
    pub deletions: Option<u64>,
    pub binary: bool,
}

/// Summary of differences between two commits or trees.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiffSummary {
    pub base: Oid,
    pub head: Oid,
    pub files: Vec<DiffFileStat>,
    pub total_additions: u64,
    pub total_deletions: u64,
}

/// Returns `true` if `ancestor` is an ancestor of `descendant` (`git merge-base --is-ancestor`).
pub async fn is_ancestor(
    repo_dir: &Path,
    ancestor: &Oid,
    descendant: &Oid,
) -> Result<bool, GitError> {
    let output = run_git_bytes(
        repo_dir,
        &[
            "merge-base",
            "--is-ancestor",
            ancestor.as_str(),
            descendant.as_str(),
        ],
        None,
        &[],
    )
    .await?;
    match output.status.code() {
        Some(0) => Ok(true),
        Some(1) => Ok(false),
        other => Err(GitError::CommandFailed {
            command: "git merge-base --is-ancestor".to_owned(),
            status: other,
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        }),
    }
}

/// Checks whether `ours` and `theirs` merge cleanly via `git merge-tree --write-tree` without touching any working tree.
pub async fn check_mergeable(
    repo_dir: &Path,
    ours: &Oid,
    theirs: &Oid,
) -> Result<MergeCheckResult, GitError> {
    let output = run_git_bytes(
        repo_dir,
        &["merge-tree", "--write-tree", ours.as_str(), theirs.as_str()],
        None,
        &[],
    )
    .await?;

    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    match output.status.code() {
        Some(0) => {
            let tree_line = stdout.lines().next().unwrap_or_default().trim();
            let tree_oid = Oid::parse(tree_line)?;
            Ok(MergeCheckResult::Clean { tree_oid })
        }
        Some(1) => {
            let mut files = BTreeSet::new();
            // Conflicted index entries precede the blank line in `merge-tree --write-tree` output as `<mode> <oid> <stage>\t<path>`.
            for line in stdout.lines().skip(1) {
                if line.is_empty() {
                    break;
                }
                if let Some((_meta, path)) = line.split_once('\t') {
                    files.insert(path.to_owned());
                }
            }
            Ok(MergeCheckResult::Conflicts {
                files: files.into_iter().collect(),
                details: stdout,
            })
        }
        other => Err(GitError::CommandFailed {
            command: "git merge-tree --write-tree".to_owned(),
            status: other,
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        }),
    }
}

/// Computes a structured per-file diff summary between `base` and `head`.
pub async fn diff_summary(
    repo_dir: &Path,
    base: &Oid,
    head: &Oid,
) -> Result<DiffSummary, GitError> {
    let output = run_git_bytes(
        repo_dir,
        &[
            "diff-tree",
            "--no-commit-id",
            "-r",
            "--numstat",
            "-z",
            base.as_str(),
            head.as_str(),
        ],
        None,
        &[],
    )
    .await?;

    if !output.status.success() {
        return Err(GitError::CommandFailed {
            command: "git diff-tree --numstat".to_owned(),
            status: output.status.code(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        });
    }

    let mut files = Vec::new();
    let mut total_additions = 0u64;
    let mut total_deletions = 0u64;

    for record in output.stdout.split(|b| *b == 0) {
        if record.is_empty() {
            continue;
        }
        let text = String::from_utf8_lossy(record);
        let mut parts = text.splitn(3, '\t');
        let Some(add_str) = parts.next() else {
            continue;
        };
        let Some(del_str) = parts.next() else {
            continue;
        };
        let Some(path) = parts.next() else {
            continue;
        };
        if add_str == "-" && del_str == "-" {
            files.push(DiffFileStat {
                path: path.to_owned(),
                additions: None,
                deletions: None,
                binary: true,
            });
        } else {
            let adds = add_str.parse::<u64>().map_err(|_| {
                GitError::InvalidInput(format!("unexpected numstat addition count {add_str:?}"))
            })?;
            let dels = del_str.parse::<u64>().map_err(|_| {
                GitError::InvalidInput(format!("unexpected numstat deletion count {del_str:?}"))
            })?;
            total_additions = total_additions.saturating_add(adds);
            total_deletions = total_deletions.saturating_add(dels);
            files.push(DiffFileStat {
                path: path.to_owned(),
                additions: Some(adds),
                deletions: Some(dels),
                binary: false,
            });
        }
    }

    Ok(DiffSummary {
        base: base.clone(),
        head: head.clone(),
        files,
        total_additions,
        total_deletions,
    })
}

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

    #[tokio::test]
    async fn ancestry_mergeability_and_diff_summary_work_on_bare_repo() {
        let dir = tempfile::tempdir().unwrap();
        CliGitStore::init_bare_at(dir.path()).await.unwrap();

        let base = create_commit_in_bare(
            dir.path(),
            "refs/heads/main",
            &[],
            &[("shared.txt", b"line1\n"), ("other.txt", b"keep\n")],
            "base",
        )
        .await;
        let ours_clean = create_commit_in_bare(
            dir.path(),
            "refs/heads/main",
            &[&base],
            &[("shared.txt", b"line1\n"), ("other.txt", b"ours\n")],
            "ours clean",
        )
        .await;
        let theirs_clean = create_commit_in_bare(
            dir.path(),
            "refs/heads/feat",
            &[&base],
            &[
                ("shared.txt", b"line1\nline2\n"),
                ("other.txt", b"keep\n"),
                ("new.txt", b"added\n"),
            ],
            "theirs clean",
        )
        .await;
        let theirs_conflict = create_commit_in_bare(
            dir.path(),
            "refs/heads/conflict",
            &[&base],
            &[("shared.txt", b"line1\n"), ("other.txt", b"theirs\n")],
            "theirs conflict",
        )
        .await;

        assert!(is_ancestor(dir.path(), &base, &ours_clean).await.unwrap());
        assert!(
            !is_ancestor(dir.path(), &ours_clean, &theirs_clean)
                .await
                .unwrap()
        );

        let clean = check_mergeable(dir.path(), &ours_clean, &theirs_clean)
            .await
            .unwrap();
        assert!(
            matches!(clean, MergeCheckResult::Clean { .. }),
            "got {clean:?}"
        );

        let conflict = check_mergeable(dir.path(), &ours_clean, &theirs_conflict)
            .await
            .unwrap();
        match conflict {
            MergeCheckResult::Conflicts { files, .. } => {
                assert_eq!(files, vec!["other.txt".to_owned()]);
            }
            other => panic!("expected conflict, got {other:?}"),
        }

        let summary = diff_summary(dir.path(), &base, &theirs_clean)
            .await
            .unwrap();
        assert_eq!(summary.total_additions, 2);
        assert_eq!(summary.total_deletions, 0);
        assert_eq!(summary.files.len(), 2);
    }
}