1use super::options::DiffOptions;
4use super::structured::StructuredFileDiff;
5use super::{count_line_changes_with_options, DiffEntry, DiffStatus};
6
7#[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#[non_exhaustive]
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28pub enum DiffDetail {
29 #[default]
31 Patch,
32 Stat,
34 NameStatus,
36 NameOnly,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub struct LineStat {
43 pub insertions: usize,
45 pub deletions: usize,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub struct DiffTotals {
52 pub files_changed: usize,
54 pub insertions: usize,
56 pub deletions: usize,
58}
59
60impl DiffTotals {
61 #[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#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct FileDiff {
79 pub path: String,
81 pub old_path: Option<String>,
83 pub status: DiffStatus,
85 pub old_mode: Option<String>,
87 pub new_mode: Option<String>,
89 pub binary: bool,
91 pub old_size: u64,
93 pub new_size: u64,
95 pub similarity: Option<u32>,
97 pub stat: Option<LineStat>,
99 pub structured: Option<StructuredFileDiff>,
101 pub combined: Option<crate::combined_diff_patch::CombinedStructuredTextDiff>,
103 pub combined_status: Option<String>,
105}
106
107impl DiffEntry {
108 #[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}