Skip to main content

gitiverse_git/
diff.rs

1use std::collections::BTreeSet;
2use std::path::Path;
3
4use crate::store::{GitError, Oid, run_git_bytes};
5
6/// Outcome of a 3-way mergeability check (`git merge-tree --write-tree`).
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum MergeCheckResult {
9    Clean { tree_oid: Oid },
10    Conflicts { files: Vec<String>, details: String },
11}
12
13/// Per-file diff line count statistics.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct DiffFileStat {
16    pub path: String,
17    pub additions: Option<u64>,
18    pub deletions: Option<u64>,
19    pub binary: bool,
20}
21
22/// Summary of differences between two commits or trees.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct DiffSummary {
25    pub base: Oid,
26    pub head: Oid,
27    pub files: Vec<DiffFileStat>,
28    pub total_additions: u64,
29    pub total_deletions: u64,
30}
31
32/// Returns `true` if `ancestor` is an ancestor of `descendant` (`git merge-base --is-ancestor`).
33pub async fn is_ancestor(
34    repo_dir: &Path,
35    ancestor: &Oid,
36    descendant: &Oid,
37) -> Result<bool, GitError> {
38    let output = run_git_bytes(
39        repo_dir,
40        &[
41            "merge-base",
42            "--is-ancestor",
43            ancestor.as_str(),
44            descendant.as_str(),
45        ],
46        None,
47        &[],
48    )
49    .await?;
50    match output.status.code() {
51        Some(0) => Ok(true),
52        Some(1) => Ok(false),
53        other => Err(GitError::CommandFailed {
54            command: "git merge-base --is-ancestor".to_owned(),
55            status: other,
56            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
57        }),
58    }
59}
60
61/// Checks whether `ours` and `theirs` merge cleanly via `git merge-tree --write-tree` without touching any working tree.
62pub async fn check_mergeable(
63    repo_dir: &Path,
64    ours: &Oid,
65    theirs: &Oid,
66) -> Result<MergeCheckResult, GitError> {
67    let output = run_git_bytes(
68        repo_dir,
69        &["merge-tree", "--write-tree", ours.as_str(), theirs.as_str()],
70        None,
71        &[],
72    )
73    .await?;
74
75    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
76    match output.status.code() {
77        Some(0) => {
78            let tree_line = stdout.lines().next().unwrap_or_default().trim();
79            let tree_oid = Oid::parse(tree_line)?;
80            Ok(MergeCheckResult::Clean { tree_oid })
81        }
82        Some(1) => {
83            let mut files = BTreeSet::new();
84            // Conflicted index entries precede the blank line in `merge-tree --write-tree` output as `<mode> <oid> <stage>\t<path>`.
85            for line in stdout.lines().skip(1) {
86                if line.is_empty() {
87                    break;
88                }
89                if let Some((_meta, path)) = line.split_once('\t') {
90                    files.insert(path.to_owned());
91                }
92            }
93            Ok(MergeCheckResult::Conflicts {
94                files: files.into_iter().collect(),
95                details: stdout,
96            })
97        }
98        other => Err(GitError::CommandFailed {
99            command: "git merge-tree --write-tree".to_owned(),
100            status: other,
101            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
102        }),
103    }
104}
105
106/// Computes a structured per-file diff summary between `base` and `head`.
107pub async fn diff_summary(
108    repo_dir: &Path,
109    base: &Oid,
110    head: &Oid,
111) -> Result<DiffSummary, GitError> {
112    let output = run_git_bytes(
113        repo_dir,
114        &[
115            "diff-tree",
116            "--no-commit-id",
117            "-r",
118            "--numstat",
119            "-z",
120            base.as_str(),
121            head.as_str(),
122        ],
123        None,
124        &[],
125    )
126    .await?;
127
128    if !output.status.success() {
129        return Err(GitError::CommandFailed {
130            command: "git diff-tree --numstat".to_owned(),
131            status: output.status.code(),
132            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
133        });
134    }
135
136    let mut files = Vec::new();
137    let mut total_additions = 0u64;
138    let mut total_deletions = 0u64;
139
140    for record in output.stdout.split(|b| *b == 0) {
141        if record.is_empty() {
142            continue;
143        }
144        let text = String::from_utf8_lossy(record);
145        let mut parts = text.splitn(3, '\t');
146        let Some(add_str) = parts.next() else {
147            continue;
148        };
149        let Some(del_str) = parts.next() else {
150            continue;
151        };
152        let Some(path) = parts.next() else {
153            continue;
154        };
155        if add_str == "-" && del_str == "-" {
156            files.push(DiffFileStat {
157                path: path.to_owned(),
158                additions: None,
159                deletions: None,
160                binary: true,
161            });
162        } else {
163            let adds = add_str.parse::<u64>().map_err(|_| {
164                GitError::InvalidInput(format!("unexpected numstat addition count {add_str:?}"))
165            })?;
166            let dels = del_str.parse::<u64>().map_err(|_| {
167                GitError::InvalidInput(format!("unexpected numstat deletion count {del_str:?}"))
168            })?;
169            total_additions = total_additions.saturating_add(adds);
170            total_deletions = total_deletions.saturating_add(dels);
171            files.push(DiffFileStat {
172                path: path.to_owned(),
173                additions: Some(adds),
174                deletions: Some(dels),
175                binary: false,
176            });
177        }
178    }
179
180    Ok(DiffSummary {
181        base: base.clone(),
182        head: head.clone(),
183        files,
184        total_additions,
185        total_deletions,
186    })
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use crate::store::CliGitStore;
193    use crate::store::test_helpers::create_commit_in_bare;
194
195    #[tokio::test]
196    async fn ancestry_mergeability_and_diff_summary_work_on_bare_repo() {
197        let dir = tempfile::tempdir().unwrap();
198        CliGitStore::init_bare_at(dir.path()).await.unwrap();
199
200        let base = create_commit_in_bare(
201            dir.path(),
202            "refs/heads/main",
203            &[],
204            &[("shared.txt", b"line1\n"), ("other.txt", b"keep\n")],
205            "base",
206        )
207        .await;
208        let ours_clean = create_commit_in_bare(
209            dir.path(),
210            "refs/heads/main",
211            &[&base],
212            &[("shared.txt", b"line1\n"), ("other.txt", b"ours\n")],
213            "ours clean",
214        )
215        .await;
216        let theirs_clean = create_commit_in_bare(
217            dir.path(),
218            "refs/heads/feat",
219            &[&base],
220            &[
221                ("shared.txt", b"line1\nline2\n"),
222                ("other.txt", b"keep\n"),
223                ("new.txt", b"added\n"),
224            ],
225            "theirs clean",
226        )
227        .await;
228        let theirs_conflict = create_commit_in_bare(
229            dir.path(),
230            "refs/heads/conflict",
231            &[&base],
232            &[("shared.txt", b"line1\n"), ("other.txt", b"theirs\n")],
233            "theirs conflict",
234        )
235        .await;
236
237        assert!(is_ancestor(dir.path(), &base, &ours_clean).await.unwrap());
238        assert!(
239            !is_ancestor(dir.path(), &ours_clean, &theirs_clean)
240                .await
241                .unwrap()
242        );
243
244        let clean = check_mergeable(dir.path(), &ours_clean, &theirs_clean)
245            .await
246            .unwrap();
247        assert!(
248            matches!(clean, MergeCheckResult::Clean { .. }),
249            "got {clean:?}"
250        );
251
252        let conflict = check_mergeable(dir.path(), &ours_clean, &theirs_conflict)
253            .await
254            .unwrap();
255        match conflict {
256            MergeCheckResult::Conflicts { files, .. } => {
257                assert_eq!(files, vec!["other.txt".to_owned()]);
258            }
259            other => panic!("expected conflict, got {other:?}"),
260        }
261
262        let summary = diff_summary(dir.path(), &base, &theirs_clean)
263            .await
264            .unwrap();
265        assert_eq!(summary.total_additions, 2);
266        assert_eq!(summary.total_deletions, 0);
267        assert_eq!(summary.files.len(), 2);
268    }
269}