1use std::path::Path;
4
5use crate::config::ConfigSet;
6use crate::diff::combined_diff_patch::{
7 format_combined_structured_body, structured_combined_diff_body, CombinedDiffWsOptions,
8 CombinedStructuredTextDiff,
9};
10use crate::diff::combined_tree_diff::{
11 combined_diff_paths_trees, combined_parent_status_char, CombinedDiffPath,
12 CombinedTreeDiffOptions,
13};
14use crate::diff::detail::{DiffDetail, DiffTotals, FileDiff, LineStat};
15use crate::diff::files::{build_file_diffs, DiffFilesOutput};
16use crate::diff::merge_diff::{
17 blob_text_for_diff, enrich_combined_path_renames, format_combined_binary, is_binary_for_diff,
18 read_blob_at_path,
19};
20use crate::diff::{DiffEntry, DiffOptions, DiffStatus};
21use crate::error::Result;
22use crate::objects::ObjectId;
23use crate::odb::Odb;
24use crate::pack_store::PackReadContextGuard;
25use crate::parallel::{try_par_map_with_local, ParallelHashError, ParallelOp, ThreadPolicy};
26use crate::repo::Repository;
27use std::sync::Arc;
28
29#[non_exhaustive]
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub enum DiffMerges {
33 FirstParent,
35 #[default]
37 Combined,
38}
39
40impl DiffMerges {
41 #[must_use]
44 pub fn parse(value: &str) -> Option<Self> {
45 match value {
46 "first-parent" | "first_parent" => Some(Self::FirstParent),
47 "combined" | "dense-combined" | "dense_combined" => Some(Self::Combined),
48 _ => None,
49 }
50 }
51}
52
53fn combined_ws(_options: &DiffOptions) -> CombinedDiffWsOptions {
54 CombinedDiffWsOptions::default()
55}
56
57fn combined_status_letters(path: &CombinedDiffPath) -> String {
58 path.parents
59 .iter()
60 .map(|s| combined_parent_status_char(s.status))
61 .collect()
62}
63
64fn file_diff_from_combined_path(path: CombinedDiffPath) -> FileDiff {
65 let combined_status = combined_status_letters(&path);
66 FileDiff {
67 path: path.path,
68 old_path: None,
69 status: DiffStatus::Modified,
70 old_mode: None,
71 new_mode: None,
72 binary: false,
73 old_size: 0,
74 new_size: 0,
75 similarity: None,
76 stat: None,
77 structured: None,
78 combined: None,
79 combined_status: Some(combined_status),
80 }
81}
82
83fn filter_combined_paths(paths: Vec<String>, pathspecs: &[String]) -> Vec<String> {
84 if pathspecs.is_empty() {
85 return paths;
86 }
87 paths
88 .into_iter()
89 .filter(|p| crate::pathspec::path_allowed_by_pathspec_list(pathspecs, p))
90 .collect()
91}
92
93#[allow(clippy::too_many_arguments)]
99pub(crate) fn commit_diff_files(
100 repo: &Repository,
101 commit_oid: &ObjectId,
102 merges: DiffMerges,
103 detail: DiffDetail,
104 options: &DiffOptions,
105 pathspec: &crate::pathspec::Pathspec,
106 thread_policy: &ThreadPolicy,
107) -> Result<DiffFilesOutput> {
108 let pathspecs = pathspec.specs();
109 let config = repo.config().snapshot()?;
110 let commit = repo.read_commit_with_replace(commit_oid)?;
111 let parent_ctx = crate::shallow::EffectiveCommitParents::load(repo);
112 let effective_parents = parent_ctx.for_commit(*commit_oid, &commit.parents);
113 if effective_parents.len() < 2 || merges == DiffMerges::FirstParent {
114 let old_tree = match effective_parents.first() {
115 Some(parent) => Some(repo.read_commit_with_replace(parent)?.tree),
116 None => None,
117 };
118 let entries = tree_diff_entries(
119 repo,
120 old_tree.as_ref(),
121 Some(&commit.tree),
122 "",
123 pathspecs,
124 config.as_ref(),
125 thread_policy,
126 )?;
127 let filtered = filter_entries(repo, entries, pathspecs)?;
128 let mut out = build_file_diffs(
129 repo.odb(),
130 filtered,
131 detail,
132 options
133 .clone()
134 .with_renames(crate::diff::RenameDetection::Off),
135 config.as_ref(),
136 thread_policy,
137 )?;
138 out.files.sort_by(|a, b| a.path.cmp(&b.path));
139 return Ok(out);
140 }
141
142 combined_commit_diff_files(
143 repo,
144 &commit.tree,
145 &effective_parents,
146 detail,
147 options,
148 pathspecs,
149 config.as_ref(),
150 thread_policy,
151 )
152}
153
154fn filter_entries(
155 repo: &Repository,
156 entries: Vec<DiffEntry>,
157 pathspecs: &[String],
158) -> Result<Vec<DiffEntry>> {
159 if pathspecs.is_empty() {
160 return Ok(entries);
161 }
162 let matcher = repo.pathspec_matcher(pathspecs)?;
163 Ok(entries
164 .into_iter()
165 .filter(|entry| {
166 let path = entry
167 .new_path
168 .as_deref()
169 .or(entry.old_path.as_deref())
170 .unwrap_or("");
171 matcher.matches_change(path, entry.old_path.as_deref())
172 })
173 .collect())
174}
175
176pub(crate) fn commit_first_parent_diff_entries(
182 repo: &Repository,
183 commit_oid: &ObjectId,
184 commit: &crate::objects::CommitData,
185 pathspecs: &[String],
186 config: &ConfigSet,
187 thread_policy: &ThreadPolicy,
188) -> Result<Vec<DiffEntry>> {
189 let odb = repo.odb();
190 let parent_ctx = crate::shallow::EffectiveCommitParents::load(repo);
191 let effective_parents = parent_ctx.for_commit(*commit_oid, &commit.parents);
192 let old_tree = match effective_parents.first() {
193 Some(parent) => Some(odb.commit_tree(parent)?),
194 None => None,
195 };
196 let entries = tree_diff_entries(
197 repo,
198 old_tree.as_ref(),
199 Some(&commit.tree),
200 "",
201 pathspecs,
202 config,
203 thread_policy,
204 )?;
205 filter_entries(repo, entries, pathspecs)
206}
207
208fn tree_diff_entries(
209 repo: &Repository,
210 old_tree: Option<&ObjectId>,
211 new_tree: Option<&ObjectId>,
212 prefix: &str,
213 pathspecs: &[String],
214 config: &ConfigSet,
215 thread_policy: &ThreadPolicy,
216) -> Result<Vec<DiffEntry>> {
217 let threshold = crate::diff::renames_from_config(config)
218 .threshold_percent()
219 .unwrap_or(crate::diff::RENAME_DETECTION_DISABLED);
220 let pathspec_matcher = if pathspecs.is_empty() {
221 None
222 } else {
223 Some(repo.pathspec_matcher(pathspecs)?)
224 };
225 crate::diff::core::diff_trees_with_renames_for_pathspecs_and_policy(
226 repo.odb(),
227 old_tree,
228 new_tree,
229 prefix,
230 pathspecs,
231 pathspec_matcher.as_ref(),
232 threshold,
233 config,
234 thread_policy,
235 )
236}
237
238#[allow(clippy::too_many_arguments)]
239fn combined_commit_diff_files(
240 repo: &Repository,
241 result_tree: &ObjectId,
242 parent_commits: &[ObjectId],
243 detail: DiffDetail,
244 options: &DiffOptions,
245 pathspecs: &[String],
246 config: &ConfigSet,
247 thread_policy: &ThreadPolicy,
248) -> Result<DiffFilesOutput> {
249 let odb = repo.odb();
250 let mut parent_trees = Vec::with_capacity(parent_commits.len());
251 for p in parent_commits {
252 parent_trees.push(odb.commit_tree(p)?);
253 }
254
255 let walk = CombinedTreeDiffOptions::default();
256 let parent_tree_opts: Vec<Option<ObjectId>> = parent_trees.iter().copied().map(Some).collect();
257 let mut paths = combined_diff_paths_trees(odb, result_tree, &parent_tree_opts, &walk, None)?;
258 let path_names: Vec<String> = paths.iter().map(|p| p.path.clone()).collect();
259 let filtered_names = filter_combined_paths(path_names, pathspecs);
260 paths.retain(|p| filtered_names.iter().any(|n| n == &p.path));
261
262 for path in &mut paths {
263 enrich_combined_path_renames(odb, path, &parent_trees, result_tree, 50);
264 }
265
266 if detail == DiffDetail::NameOnly {
267 let files: Vec<FileDiff> = paths
268 .into_iter()
269 .map(|path| FileDiff {
270 path: path.path,
271 old_path: None,
272 status: DiffStatus::Modified,
273 old_mode: None,
274 new_mode: None,
275 binary: false,
276 old_size: 0,
277 new_size: 0,
278 similarity: None,
279 stat: None,
280 structured: None,
281 combined: None,
282 combined_status: None,
283 })
284 .collect();
285 return Ok(DiffFilesOutput {
286 files,
287 totals: None,
288 inexact_rename_skipped: None,
289 });
290 }
291 if detail == DiffDetail::NameStatus {
292 let files: Vec<FileDiff> = paths
293 .into_iter()
294 .map(file_diff_from_combined_path)
295 .collect();
296 return Ok(DiffFilesOutput {
297 files,
298 totals: None,
299 inexact_rename_skipped: None,
300 });
301 }
302
303 let git_dir = repo.git_dir();
304 let ws = combined_ws(options);
305 let context = options.context_lines;
306 let par_opts = thread_policy.resolve(ParallelOp::DiffContent, config);
307 let store = odb.pack_store_for(odb.objects_dir());
308 let result_tree = *result_tree;
309 let rows = try_par_map_with_local(
310 &paths,
311 par_opts,
312 0,
313 || PackReadContextGuard::install(Arc::clone(&store)),
314 |_ctx, path| {
315 combined_path_file_diff(git_dir, config, odb, path, result_tree, detail, context, ws)
316 },
317 );
318 let rows = match rows {
319 Ok(rows) => rows,
320 Err(ParallelHashError::Task(err)) => return Err(err),
321 };
322
323 let mut files = Vec::with_capacity(rows.len());
324 let mut insertions = 0usize;
325 let mut deletions = 0usize;
326 for (file, stat) in rows {
327 if let Some(s) = stat {
328 insertions += s.insertions;
329 deletions += s.deletions;
330 }
331 files.push(file);
332 }
333 files.sort_by(|a, b| a.path.cmp(&b.path));
334
335 let totals = if detail == DiffDetail::Stat {
336 Some(DiffTotals {
337 files_changed: files.len(),
338 insertions,
339 deletions,
340 })
341 } else {
342 None
343 };
344 Ok(DiffFilesOutput {
345 files,
346 totals,
347 inexact_rename_skipped: None,
348 })
349}
350
351#[allow(clippy::too_many_arguments)]
352fn combined_path_file_diff(
353 git_dir: &Path,
354 config: &ConfigSet,
355 odb: &Odb,
356 path: &CombinedDiffPath,
357 result_tree: ObjectId,
358 detail: DiffDetail,
359 context: usize,
360 ws: CombinedDiffWsOptions,
361) -> Result<(FileDiff, Option<LineStat>)> {
362 let (parent_blobs, result_blob) = load_combined_path_blobs(odb, path, &result_tree)?;
363 let binary =
364 combined_path_is_binary_from_blobs(git_dir, &path.path, &parent_blobs, &result_blob);
365 if binary {
366 let parent_oids: Vec<ObjectId> = path.parents.iter().map(|s| s.oid).collect();
367 let _patch = format_combined_binary(&path.path, &parent_oids, &path.merge_oid, 7, true);
368 return Ok((
369 FileDiff {
370 path: path.path.clone(),
371 old_path: None,
372 status: DiffStatus::Modified,
373 old_mode: None,
374 new_mode: None,
375 binary: true,
376 old_size: 0,
377 new_size: 0,
378 similarity: None,
379 stat: if detail == DiffDetail::Stat {
380 Some(LineStat::default())
381 } else {
382 None
383 },
384 structured: None,
385 combined: None,
386 combined_status: Some(combined_status_letters(path)),
387 },
388 None,
389 ));
390 }
391
392 let mut parent_texts = Vec::with_capacity(path.parents.len());
393 for (i, side) in path.parents.iter().enumerate() {
394 let text = if side.oid.is_zero() {
395 String::new()
396 } else {
397 blob_text_for_diff(git_dir, config, &path.path, &parent_blobs[i], false)
398 };
399 parent_texts.push(text);
400 }
401 let result_text = blob_text_for_diff(git_dir, config, &path.path, &result_blob, false);
402 let combined = structured_combined_diff_body(&parent_texts, &result_text, context, true, ws);
403 let stat = match detail {
404 DiffDetail::Stat => Some(combined.line_stat()),
405 _ => None,
406 };
407 Ok((
408 FileDiff {
409 path: path.path.clone(),
410 old_path: None,
411 status: DiffStatus::Modified,
412 old_mode: None,
413 new_mode: None,
414 binary: false,
415 old_size: 0,
416 new_size: 0,
417 similarity: None,
418 stat,
419 structured: None,
420 combined: Some(combined),
421 combined_status: Some(combined_status_letters(path)),
422 },
423 stat,
424 ))
425}
426
427fn load_combined_path_blobs(
428 odb: &Odb,
429 path: &CombinedDiffPath,
430 result_tree: &ObjectId,
431) -> Result<(Vec<Vec<u8>>, Vec<u8>)> {
432 let mut parent_blobs = Vec::with_capacity(path.parents.len());
433 for side in &path.parents {
434 if side.oid.is_zero() {
435 parent_blobs.push(Vec::new());
436 } else {
437 parent_blobs.push(odb.read(&side.oid)?.data);
438 }
439 }
440 let result_blob = read_blob_at_path(odb, result_tree, &path.path).unwrap_or_default();
441 Ok((parent_blobs, result_blob))
442}
443
444fn combined_path_is_binary_from_blobs(
445 git_dir: &Path,
446 path: &str,
447 parent_blobs: &[Vec<u8>],
448 result_blob: &[u8],
449) -> bool {
450 if is_binary_for_diff(git_dir, path, result_blob) {
451 return true;
452 }
453 parent_blobs
454 .iter()
455 .any(|blob| !blob.is_empty() && is_binary_for_diff(git_dir, path, blob))
456}
457
458#[must_use]
460pub fn combined_structured_patch_body(diff: &CombinedStructuredTextDiff) -> String {
461 format_combined_structured_body(diff)
462}