Skip to main content

grit_lib/diff/
detail.rs

1//! Per-file diff detail levels (patch, stat, name-only) and aggregate totals.
2
3use super::options::DiffOptions;
4use super::structured::StructuredFileDiff;
5use super::{count_line_changes_with_options, DiffEntry, DiffStatus};
6
7/// Count insertions and deletions between two text sides using [`DiffOptions`]'s algorithm.
8///
9/// Does not allocate hunk structures (used for `--stat` / `--numstat`). Counts follow the
10/// same compacted line alignment as structured patches for the same [`DiffOptions`].
11#[must_use]
12pub(crate) fn line_stat_for_options(
13    old_content: &str,
14    new_content: &str,
15    options: &DiffOptions,
16) -> LineStat {
17    let (insertions, deletions) =
18        count_line_changes_with_options(old_content, new_content, options);
19    LineStat {
20        insertions,
21        deletions,
22    }
23}
24
25/// How much content to compute for each changed file.
26#[non_exhaustive]
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28pub enum DiffDetail {
29    /// Full structured line hunks.
30    #[default]
31    Patch,
32    /// Insertion/deletion counts only (`--stat`, `--numstat`, `--shortstat`).
33    Stat,
34    /// `git diff --name-status` (status letter and paths).
35    NameStatus,
36    /// `git diff --name-only` (paths only).
37    NameOnly,
38}
39
40/// Line insertion/deletion counts for one file (`--numstat`).
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub struct LineStat {
43    /// Lines added on the new side.
44    pub insertions: usize,
45    /// Lines removed from the old side.
46    pub deletions: usize,
47}
48
49/// Summary across all files in a stat-style diff.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub struct DiffTotals {
52    /// Number of changed paths.
53    pub files_changed: usize,
54    /// Total insertions across text files.
55    pub insertions: usize,
56    /// Total deletions across text files.
57    pub deletions: usize,
58}
59
60impl DiffTotals {
61    /// Sum per-file stats into totals (binary files contribute to `files_changed` only).
62    #[must_use]
63    pub fn from_files(files: &[FileDiff]) -> Self {
64        let lines: LineStat = files.iter().filter_map(|file| file.stat).sum();
65        Self {
66            files_changed: files.len(),
67            insertions: lines.insertions,
68            deletions: lines.deletions,
69        }
70    }
71}
72
73/// One changed file with optional patch body or line counts (returned by [`Diff::files_for_entries`](crate::diff::Diff::files_for_entries)).
74///
75/// Re-exported at the crate root as [`ListedFileDiff`](crate::diff::ListedFileDiff). Use
76/// [`crate::diff::targets::FileDiff`] when you need structured hunks from [`Diff::files`](crate::diff::Diff::files).
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct FileDiff {
79    /// Display path (new side, or old for deletions).
80    pub path: String,
81    /// Pre-rename path when it differs from [`Self::path`].
82    pub old_path: Option<String>,
83    /// Change kind.
84    pub status: DiffStatus,
85    /// Old git mode (octal), when present.
86    pub old_mode: Option<String>,
87    /// New git mode (octal), when present.
88    pub new_mode: Option<String>,
89    /// Either side looks like a binary blob.
90    pub binary: bool,
91    /// Old-side byte length (for binary `--stat` and JSON).
92    pub old_size: u64,
93    /// New-side byte length (for binary `--stat` and JSON).
94    pub new_size: u64,
95    /// Rename/copy similarity (0–100), when applicable.
96    pub similarity: Option<u32>,
97    /// Line counts when [`DiffDetail::Stat`] was requested.
98    pub stat: Option<LineStat>,
99    /// Structured hunks when [`DiffDetail::Patch`] was requested.
100    pub structured: Option<StructuredFileDiff>,
101    /// Combined (`--cc`) hunks for merge commits; mutually exclusive with [`Self::structured`].
102    pub combined: Option<crate::combined_diff_patch::CombinedStructuredTextDiff>,
103    /// Per-parent status letters for combined merge name-status (e.g. `MM`, `DD`).
104    pub combined_status: Option<String>,
105}
106
107impl DiffEntry {
108    /// Similarity index for renames and copies (`DiffEntry::score`).
109    #[must_use]
110    pub fn rename_similarity(&self) -> Option<u32> {
111        match self.status {
112            DiffStatus::Renamed | DiffStatus::Copied => self.score,
113            _ => None,
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use crate::diff::options::DiffAlgorithm;
122    use crate::diff::structured::{structured_file_diff, SideBytes};
123    use crate::objects::FileMode;
124
125    fn patch_oracle_stat(old: &str, new: &str, options: &DiffOptions) -> LineStat {
126        let structured = structured_file_diff(
127            FileMode::REGULAR,
128            FileMode::REGULAR,
129            &SideBytes::from_bytes(old.as_bytes().to_vec()),
130            &SideBytes::from_bytes(new.as_bytes().to_vec()),
131            options.clone(),
132        );
133        LineStat::from_hunks(&structured.hunks)
134    }
135
136    fn git_numstat(old: &str, new: &str, algorithm: DiffAlgorithm) -> LineStat {
137        let dir = tempfile::tempdir().expect("tempdir");
138        std::fs::write(dir.path().join("old"), old).expect("old");
139        std::fs::write(dir.path().join("new"), new).expect("new");
140        let algo = match algorithm {
141            DiffAlgorithm::Myers => "myers",
142            DiffAlgorithm::Minimal => "minimal",
143            DiffAlgorithm::Patience => "patience",
144            DiffAlgorithm::Histogram => "histogram",
145        };
146        let out = std::process::Command::new("git")
147            .args([
148                "diff",
149                "--no-index",
150                "--numstat",
151                &format!("--diff-algorithm={algo}"),
152                "old",
153                "new",
154            ])
155            .current_dir(dir.path())
156            .env("GIT_CONFIG_GLOBAL", "/dev/null")
157            .env("GIT_CONFIG_SYSTEM", "/dev/null")
158            .env("GIT_CONFIG_NOSYSTEM", "1")
159            .output()
160            .expect("git diff");
161        assert!(
162            out.status.success() || out.status.code() == Some(1),
163            "git diff failed: {}",
164            String::from_utf8_lossy(&out.stderr)
165        );
166        let line = String::from_utf8_lossy(&out.stdout);
167        let line = line.lines().next().unwrap_or("");
168        let mut parts = line.split('\t');
169        let ins = parts.next().unwrap_or("0").parse().unwrap_or(0);
170        let del = parts.next().unwrap_or("0").parse().unwrap_or(0);
171        LineStat {
172            insertions: ins,
173            deletions: del,
174        }
175    }
176
177    #[test]
178    fn myers_stat_preserves_line_boundaries_and_repeated_lines() {
179        let options = DiffOptions::default();
180        let texts = [
181            "",
182            "a",
183            "a\n",
184            "a\na",
185            "a\na\n",
186            "a\nb\na\n",
187            "b\na\nb\n",
188            "\n",
189            "\n\n",
190            "a\r",
191            "a\r\n",
192            "a\rb\n",
193            "é\n猫",
194            "é\n猫\n",
195            "a\n\r\nb\n",
196        ];
197        for old in texts {
198            for new in texts {
199                let grit = line_stat_for_options(old, new, &options);
200                let patch = patch_oracle_stat(old, new, &options);
201                assert_eq!(grit, patch, "patch oracle: old={old:?}, new={new:?}");
202                if !old.contains('\r') && !new.contains('\r') {
203                    let git = git_numstat(old, new, DiffAlgorithm::Myers);
204                    assert_eq!(grit, git, "git numstat: old={old:?}, new={new:?}");
205                }
206            }
207        }
208
209        let mut seed = 4687u64;
210        for iteration in 0..500 {
211            let mut text = || {
212                (0..160)
213                    .map(|_| {
214                        seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
215                        match seed >> 61 {
216                            0..=3 => "repeat\n",
217                            4 => "é\r\n",
218                            5 => "\n",
219                            6 => "x\ry\n",
220                            _ => "tail\n",
221                        }
222                    })
223                    .collect::<String>()
224            };
225            let (mut old, mut new) = (text(), text());
226            if iteration % 2 == 0 {
227                old = old.replace('\r', "");
228                new = new.replace('\r', "");
229            }
230            let prefix = "unchanged\n".repeat(120);
231            let old = format!("{prefix}{old}{prefix}");
232            let new = format!("{prefix}{new}{prefix}");
233            let grit = line_stat_for_options(&old, &new, &options);
234            let patch = patch_oracle_stat(&old, &new, &options);
235            assert_eq!(grit, patch, "random iteration {iteration}");
236        }
237    }
238
239    #[test]
240    fn myers_stat_large_file_small_edit() {
241        let options = DiffOptions::default();
242        let prefix = "unchanged prefix\n".repeat(10_000);
243        let suffix = "unchanged suffix\n".repeat(10_000);
244        let old = format!("{prefix}old\n{suffix}");
245        let new = format!("{prefix}new\nextra\n{suffix}");
246        let grit = line_stat_for_options(&old, &new, &options);
247        assert_eq!(
248            grit,
249            LineStat {
250                insertions: 2,
251                deletions: 1,
252            }
253        );
254        assert_eq!(grit, patch_oracle_stat(&old, &new, &options));
255        assert_eq!(grit, git_numstat(&old, &new, DiffAlgorithm::Myers));
256    }
257
258    #[test]
259    fn myers_stat_repetitive_po_like_fixture_matches_git() {
260        let options = DiffOptions::default();
261        let repeated = "msgid \"entry\"\nmsgstr \"same translation line\"\n".repeat(15_000);
262        let mut old = repeated.clone();
263        old.push_str("msgid \"removed\"\nmsgstr \"gone\"\n");
264        let mut new = repeated;
265        new.push_str("msgid \"added-a\"\nmsgstr \"one\"\n");
266        new.push_str("msgid \"added-b\"\nmsgstr \"two\"\n");
267        let grit = line_stat_for_options(&old, &new, &options);
268        let git = git_numstat(&old, &new, DiffAlgorithm::Myers);
269        assert_eq!(grit, git, "repetitive .po-like numstat vs git");
270        assert_eq!(grit, patch_oracle_stat(&old, &new, &options));
271    }
272
273    #[test]
274    fn line_stat_matches_git_and_repeated_anchor_fixture() {
275        let anchor = "fn anchor() {\n";
276        let old = format!("{anchor}{anchor}// old body\n");
277        let mut new = String::new();
278        for i in 0..800 {
279            new.push_str(&format!("// inserted block {i}\n"));
280        }
281        new.push_str(&anchor);
282        new.push_str("// new tail\n");
283
284        for algorithm in [
285            DiffAlgorithm::Myers,
286            DiffAlgorithm::Minimal,
287            DiffAlgorithm::Patience,
288            DiffAlgorithm::Histogram,
289        ] {
290            let options = DiffOptions::default()
291                .with_algorithm(algorithm)
292                .with_indent_heuristic(true);
293            let grit = line_stat_for_options(&old, &new, &options);
294            let git = git_numstat(&old, &new, algorithm);
295            assert_eq!(grit, git, "{algorithm:?} numstat vs git");
296        }
297    }
298}