1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
//! Per-file diff detail levels (patch, stat, name-only) and aggregate totals.
use super::options::{DiffAlgorithm, DiffOptions};
use super::structured::StructuredFileDiff;
use super::{count_changes_with_algorithm, DiffEntry, DiffStatus};
/// Count insertions and deletions between two text sides using [`DiffOptions`]'s algorithm.
///
/// Does not allocate hunk structures (used for `--stat` / `--numstat`). Myers
/// comparisons trim identical boundary lines before allocating line tokens, so
/// small edits in large files need tokens only for the changed region.
#[must_use]
pub fn line_change_counts(old_content: &str, new_content: &str, options: &DiffOptions) -> LineStat {
let (old_content, new_content) = if options.algorithm == DiffAlgorithm::Myers {
changed_region(old_content, new_content)
} else {
(old_content, new_content)
};
if options.algorithm == DiffAlgorithm::Myers
&& !old_content.as_bytes().contains(&b'\r')
&& !new_content.as_bytes().contains(&b'\r')
{
return myers_lf_counts(old_content, new_content);
}
let (insertions, deletions) = count_changes_with_algorithm(
old_content,
new_content,
options.algorithm.similar_algorithm(),
options.algorithm.uses_git_histogram(),
);
LineStat {
insertions,
deletions,
}
}
fn myers_lf_counts(old: &str, new: &str) -> LineStat {
if old.is_empty() || new.is_empty() {
return LineStat {
insertions: new.split_inclusive('\n').count(),
deletions: old.split_inclusive('\n').count(),
};
}
// Borrow line slices and use the same compact interner as the patch engine.
// The text adapter otherwise scans Unicode characters and constructs a much
// larger comparison table before Myers can run. CR-containing input keeps
// the text adapter's special CR/CRLF tokenization above.
let (old_ids, new_ids) = {
let old_lines: Vec<_> = old.split_inclusive('\n').collect();
let new_lines: Vec<_> = new.split_inclusive('\n').collect();
let mut interner =
crate::line_interner::LineInterner::with_capacity(old_lines.len() + new_lines.len());
(
interner.intern_all(&old_lines),
interner.intern_all(&new_lines),
)
};
let mut stat = LineStat::default();
for op in similar::capture_diff_slices(similar::Algorithm::Myers, &old_ids, &new_ids) {
match op {
similar::DiffOp::Delete { old_len, .. } => stat.deletions += old_len,
similar::DiffOp::Insert { new_len, .. } => stat.insertions += new_len,
similar::DiffOp::Replace {
old_len, new_len, ..
} => {
stat.deletions += old_len;
stat.insertions += new_len;
}
similar::DiffOp::Equal { .. } => {}
}
}
stat
}
// Myers already discards equal boundary tokens. Do that before tokenization as
// well, without allocating a token or comparison-table entry for every line.
// Keep delimiters in the comparison so an EOF newline change remains visible.
fn changed_region<'a>(old: &'a str, new: &'a str) -> (&'a str, &'a str) {
let prefix: usize = old
.split_inclusive('\n')
.zip(new.split_inclusive('\n'))
.take_while(|(a, b)| a == b)
.map(|(line, _)| line.len())
.sum();
let (old, new) = (&old[prefix..], &new[prefix..]);
let suffix: usize = old
.split_inclusive('\n')
.rev()
.zip(new.split_inclusive('\n').rev())
.take_while(|(a, b)| a == b)
.map(|(line, _)| line.len())
.sum();
(&old[..old.len() - suffix], &new[..new.len() - suffix])
}
/// How much content to compute for each changed file.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DiffDetail {
/// Full structured line hunks.
#[default]
Patch,
/// Insertion/deletion counts only (`--stat`, `--numstat`, `--shortstat`).
Stat,
/// `git diff --name-status` (status letter and paths).
NameStatus,
/// `git diff --name-only` (paths only).
NameOnly,
}
/// Line insertion/deletion counts for one file (`--numstat`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct LineStat {
/// Lines added on the new side.
pub insertions: usize,
/// Lines removed from the old side.
pub deletions: usize,
}
/// Summary across all files in a stat-style diff.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DiffTotals {
/// Number of changed paths.
pub files_changed: usize,
/// Total insertions across text files.
pub insertions: usize,
/// Total deletions across text files.
pub deletions: usize,
}
impl DiffTotals {
/// Sum per-file stats into totals (binary files contribute to `files_changed` only).
#[must_use]
pub fn from_files(files: &[FileDiff]) -> Self {
let mut insertions = 0usize;
let mut deletions = 0usize;
for file in files {
if let Some(stat) = file.stat {
insertions += stat.insertions;
deletions += stat.deletions;
}
}
Self {
files_changed: files.len(),
insertions,
deletions,
}
}
}
/// One changed file with optional patch body or line counts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileDiff {
/// Display path (new side, or old for deletions).
pub path: String,
/// Pre-rename path when it differs from [`Self::path`].
pub old_path: Option<String>,
/// Change kind.
pub status: DiffStatus,
/// Old git mode (octal), when present.
pub old_mode: Option<String>,
/// New git mode (octal), when present.
pub new_mode: Option<String>,
/// Either side looks like a binary blob.
pub binary: bool,
/// Rename/copy similarity (0–100), when applicable.
pub similarity: Option<u32>,
/// Line counts when [`DiffDetail::Stat`] was requested.
pub stat: Option<LineStat>,
/// Structured hunks when [`DiffDetail::Patch`] was requested.
pub structured: Option<StructuredFileDiff>,
/// Combined (`--cc`) hunks for merge commits; mutually exclusive with [`Self::structured`].
pub combined: Option<crate::combined_diff_patch::CombinedStructuredTextDiff>,
/// Per-parent status letters for combined merge name-status (e.g. `MM`, `DD`).
pub combined_status: Option<String>,
}
impl DiffEntry {
/// Similarity index for renames and copies (`DiffEntry::score`).
#[must_use]
pub fn rename_similarity(&self) -> Option<u32> {
match self.status {
DiffStatus::Renamed | DiffStatus::Copied => self.score,
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn reference_counts(old: &str, new: &str) -> LineStat {
let (insertions, deletions) =
count_changes_with_algorithm(old, new, similar::Algorithm::Myers, false);
LineStat {
insertions,
deletions,
}
}
#[test]
fn myers_stat_preserves_line_boundaries_and_repeated_lines() {
let options = DiffOptions::default();
let texts = [
"",
"a",
"a\n",
"a\na",
"a\na\n",
"a\nb\na\n",
"b\na\nb\n",
"\n",
"\n\n",
"a\r",
"a\r\n",
"a\rb\n",
"é\n猫",
"é\n猫\n",
"a\n\r\nb\n",
];
for old in texts {
for new in texts {
assert_eq!(
line_change_counts(old, new, &options),
reference_counts(old, new),
"old={old:?}, new={new:?}"
);
}
}
// Cross the line-interning threshold with repeated lines and edits at
// different offsets, including insertions beside identical boundary lines.
let mut seed = 4687u64;
for iteration in 0..500 {
let mut text = || {
(0..160)
.map(|_| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
match seed >> 61 {
0..=3 => "repeat\n",
4 => "é\r\n",
5 => "\n",
6 => "x\ry\n",
_ => "tail\n",
}
})
.collect::<String>()
};
let (mut old, mut new) = (text(), text());
if iteration % 2 == 0 {
old = old.replace('\r', "");
new = new.replace('\r', "");
}
let prefix = "unchanged\n".repeat(120);
let old = format!("{prefix}{old}{prefix}");
let new = format!("{prefix}{new}{prefix}");
assert_eq!(
line_change_counts(&old, &new, &options),
reference_counts(&old, &new)
);
}
}
#[test]
fn myers_stat_large_file_small_edit() {
let prefix = "unchanged prefix\n".repeat(10_000);
let suffix = "unchanged suffix\n".repeat(10_000);
let old = format!("{prefix}old\n{suffix}");
let new = format!("{prefix}new\nextra\n{suffix}");
assert_eq!(changed_region(&old, &new), ("old\n", "new\nextra\n"));
assert_eq!(
line_change_counts(&old, &new, &DiffOptions::default()),
LineStat {
insertions: 2,
deletions: 1,
}
);
assert_eq!(changed_region(&old, &old), ("", ""));
}
}