Skip to main content

grit_lib/diff/
handle.rs

1//! Repository-scoped tree, index and work-tree diffs via [`Diff`].
2
3#![allow(deprecated)]
4
5use std::path::Path;
6
7use crate::diff::targets::{collect_files_for_target, limit_target_entries, stored_target_entries};
8use crate::diff::{
9    detect_renames_with_policy, diff_index_to_tree, diff_index_to_worktree_with_options,
10    diff_tree_to_worktree_with_git_dir_and_rules_extras, diff_trees_for_pathspecs_at,
11    index_mtime_for_diff, postprocess_diff_entries, postprocess_diff_entries_from_sources,
12    tree_oid_of_commit, DetectRenamesOptions, DiffDetail, DiffEntriesResult, DiffEntry,
13    DiffFilesOutput, DiffIndexToWorktreeOptions, DiffMerges, DiffOptions, DiffPostprocessWorktree,
14    DiffStat, DiffTreeToWorktreeExtras, ListedFileDiff, TreeDiffOptions, TreeDiffStructured,
15};
16use crate::diff::{
17    DiffArguments, DiffRequest, DiffTarget, FileChange, FileDiff, HunkDiffBundle, UncommittedDiff,
18};
19use crate::error::Result;
20use crate::index::Index;
21use crate::objects::{FileMode, ObjectId};
22use crate::parallel::ThreadPolicy;
23use crate::pathspec::{Pathspec, PathspecMatcher};
24use crate::repo::Repository;
25use crate::repo::RepositoryError;
26use crate::submodule_ignore::SubmoduleIgnoreMode;
27
28/// Compare trees, the index, and the working tree for one repository.
29///
30/// Obtain it from [`Repository::diff`]. The metadata diffs ([`Self::tree_to_tree`],
31/// [`Self::commits`], [`Self::index_to_tree`], [`Self::index_to_worktree`],
32/// [`Self::tree_to_worktree`]) list changed paths without loading contents and take one
33/// [`TreeDiffOptions`]; the content methods ([`Self::files_for_entries`], [`Self::stat`],
34/// [`Self::structured`], [`Self::for_each_structured`], …) turn those entries into hunks and
35/// line counts under a [`DiffOptions`]. Configuration is read from the repository.
36#[derive(Debug, Copy, Clone)]
37pub struct Diff<'repo> {
38    repo: &'repo Repository,
39}
40
41impl<'repo> Diff<'repo> {
42    /// Bind diff helpers to `repo`.
43    #[inline]
44    #[must_use]
45    pub fn new(repo: &'repo Repository) -> Self {
46        Self { repo }
47    }
48
49    /// Underlying repository.
50    #[inline]
51    #[must_use]
52    pub fn repository(&self) -> &'repo Repository {
53        self.repo
54    }
55
56    /// Diff two tree oids (either side may be `None` for an empty tree).
57    ///
58    /// Reads tree metadata without loading blobs and skips identical subtree ids; with a
59    /// pathspec, directories it cannot reach are not read. Rename, copy and break pairing
60    /// follow `options` (none by default). The walk retains active directory frames alongside
61    /// the ODB's bounded tree cache; the result owns metadata for every changed path.
62    ///
63    /// # Parameters
64    ///
65    /// - `old_tree` - old side, or `None` for the empty tree.
66    /// - `new_tree` - new side, or `None` for the empty tree.
67    /// - `options` - pathspec, pairing, [`prefix`](TreeDiffOptions::prefix) and
68    ///   [`show_tree_entries`](TreeDiffOptions::show_tree_entries).
69    ///
70    /// # Errors
71    ///
72    /// Propagates ODB read, tree walk, pathspec and rename detection errors.
73    ///
74    /// # Examples
75    ///
76    /// ```rust
77    /// use grit_lib::diff::{DiffStatus, RenameDetection, TreeDiffOptions};
78    /// use grit_lib::objects::{serialize_tree, ObjectKind, TreeEntry};
79    /// use grit_lib::repo::{InitOptions, Repository};
80    /// # fn main() -> grit_lib::error::Result<()> {
81    /// let dir = tempfile::tempdir()?;
82    /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
83    /// let blob = repo.odb().write(ObjectKind::Blob, b"one\ntwo\nthree\n")?;
84    /// let tree = |name: &str| {
85    ///     let entry = TreeEntry {
86    ///         mode: 0o100644,
87    ///         name: name.as_bytes().to_vec(),
88    ///         oid: blob,
89    ///     };
90    ///     repo.odb().write(ObjectKind::Tree, &serialize_tree(&[entry]))
91    /// };
92    /// let (old, new) = (tree("a.txt")?, tree("b.txt")?);
93    ///
94    /// let plain = repo.diff().tree_to_tree(Some(&old), Some(&new), &TreeDiffOptions::default())?;
95    /// assert_eq!(plain.entries.len(), 2); // a.txt deleted, b.txt added
96    ///
97    /// let options = TreeDiffOptions::default().with_renames(RenameDetection::Similarity(50));
98    /// let renamed = repo.diff().tree_to_tree(Some(&old), Some(&new), &options)?;
99    /// assert_eq!(renamed.entries.len(), 1);
100    /// assert_eq!(renamed.entries[0].status, DiffStatus::Renamed);
101    /// # Ok(())
102    /// # }
103    /// ```
104    ///
105    /// See also the library guide on [diffing](https://grit-scm.com/docs/library/diff/).
106    pub fn tree_to_tree(
107        &self,
108        old_tree: Option<&ObjectId>,
109        new_tree: Option<&ObjectId>,
110        options: &TreeDiffOptions,
111    ) -> Result<DiffEntriesResult> {
112        let specs = options.pathspec_specs();
113        let matcher = self.matcher(options)?;
114        let mut entries = diff_trees_for_pathspecs_at(
115            self.repo.odb(),
116            old_tree,
117            new_tree,
118            &options.prefix,
119            options.show_tree_entries,
120            specs,
121            matcher.as_ref(),
122        )?;
123        retain_submodule_entries(&mut entries, options.submodules);
124        self.pair_with_tree_sources(entries, old_tree, None, None, options)
125    }
126
127    /// Diff the trees recorded at two commits (`base` is the old side, `tip` the new side).
128    ///
129    /// Same as [`Self::tree_to_tree`] on the commits' trees.
130    ///
131    /// # Errors
132    ///
133    /// Returns [`RefError::Invalid`](crate::error::RefError::Invalid) when either id is not a
134    /// commit, plus the errors of [`Self::tree_to_tree`].
135    pub fn commits(
136        &self,
137        base: &ObjectId,
138        tip: &ObjectId,
139        options: &TreeDiffOptions,
140    ) -> Result<DiffEntriesResult> {
141        let odb = self.repo.odb();
142        let base_tree = tree_oid_of_commit(odb, base)?;
143        let tip_tree = tree_oid_of_commit(odb, tip)?;
144        self.tree_to_tree(Some(&base_tree), Some(&tip_tree), options)
145    }
146
147    /// Diff the index against a tree (typically `HEAD`'s tree, Git `diff --cached`).
148    ///
149    /// Uses the index's cache tree to skip unchanged directories when it is valid.
150    /// [`SubmoduleIgnoreMode::All`] omits gitlink paths.
151    ///
152    /// # Parameters
153    ///
154    /// - `index` - the index to compare (the new side).
155    /// - `tree` - the old side, or `None` for the empty tree.
156    /// - `options` - pathspec, pairing and submodule policy.
157    ///
158    /// # Errors
159    ///
160    /// Propagates ODB, index diff, pathspec and rename detection errors.
161    pub fn index_to_tree(
162        &self,
163        index: &Index,
164        tree: Option<&ObjectId>,
165        options: &TreeDiffOptions,
166    ) -> Result<DiffEntriesResult> {
167        let ignore_submodules = options.submodules == SubmoduleIgnoreMode::All;
168        let mut entries = diff_index_to_tree(self.repo.odb(), index, tree, ignore_submodules)?;
169        self.retain_pathspec(&mut entries, options)?;
170        self.pair_with_tree_sources(entries, tree, None, None, options)
171    }
172
173    /// Diff the working tree against the index (Git `diff-files`).
174    ///
175    /// Entries whose stat data matches the index are not read; a changed file's work-tree
176    /// side carries a null `new_oid` unless its content had to be hashed to prove it changed.
177    /// With a pathspec only the paths it selects are scanned. Submodule checkouts are
178    /// compared per [`TreeDiffOptions::submodules`]. With
179    /// [`TreeDiffOptions::refresh_index_stat`] unchanged entries adopt fresh stat data in
180    /// `index`; nothing is written to disk.
181    ///
182    /// # Errors
183    ///
184    /// Returns [`RepositoryError::RequiresWorkTree`] in a bare repository, and work-tree I/O,
185    /// ODB, pathspec and rename detection errors.
186    pub fn index_to_worktree(
187        &self,
188        index: &mut Index,
189        options: &TreeDiffOptions,
190    ) -> Result<DiffEntriesResult> {
191        let work_tree = self.work_tree()?;
192        let config = self.repo.config().snapshot()?;
193        let restrict_to_paths = crate::diff::changes::pathspec_restrict_paths_for_scan(
194            self.repo,
195            index,
196            options.pathspec_specs(),
197            None,
198        )?;
199        let submodules = options.submodules;
200        let scan = DiffIndexToWorktreeOptions {
201            index_mtime: index_mtime_for_diff(index, None),
202            ignore_submodule_untracked: submodules != SubmoduleIgnoreMode::None,
203            simplify_gitlinks: matches!(
204                submodules,
205                SubmoduleIgnoreMode::Dirty | SubmoduleIgnoreMode::All
206            ),
207            repository_git_dir: Some(self.repo.git_dir().to_path_buf()),
208            refresh_index_stat_in_pass: options.refresh_index_stat,
209            config: Some(config),
210            thread_policy: Some(self.thread_policy(options)),
211            for_status: options.for_status,
212            refresh_fsmonitor: restrict_to_paths.is_none(),
213            command_runner: Some(self.repo.command_runner()),
214            restrict_to_paths,
215            ..DiffIndexToWorktreeOptions::default()
216        };
217        let (mut entries, index_stat_refreshed) =
218            diff_index_to_worktree_with_options(self.repo.odb(), index, work_tree, scan)?;
219        self.retain_pathspec(&mut entries, options)?;
220        retain_submodule_entries(&mut entries, submodules);
221        let mut result = if options.copies == crate::diff::CopyDetection::Off {
222            self.pair_with_tree_sources(entries, None, Some(work_tree), None, options)?
223        } else {
224            let sources: Vec<(String, FileMode, ObjectId)> = index
225                .entries
226                .iter()
227                .filter(|e| e.stage() == 0 && !e.is_sparse_directory_placeholder())
228                .map(|e| {
229                    (
230                        String::from_utf8_lossy(&e.path).into_owned(),
231                        FileMode::new(e.mode),
232                        e.oid,
233                    )
234                })
235                .collect();
236            self.pair_with_sources(entries, &sources, Some(work_tree), None, false, options)?
237        };
238        result.index_stat_refreshed = index_stat_refreshed;
239        Ok(result)
240    }
241
242    /// Diff the working tree against a tree, through `index` (Git `diff <tree>`).
243    ///
244    /// When the index's cache tree matches `tree`, this is the cheaper index-to-work-tree
245    /// scan; otherwise the tree is walked against the work tree. Work-tree bytes go through
246    /// the repository's attributes and clean filters. Break-rewrite pairing fills the
247    /// work-tree side's blob id like Git. [`SubmoduleIgnoreMode::All`] omits gitlink paths;
248    /// the other modes compare a submodule's checked-out commit.
249    ///
250    /// # Parameters
251    ///
252    /// - `tree` - the old side, or `None` for the empty tree.
253    /// - `index` - the index tracking the work tree.
254    /// - `options` - pathspec, pairing and submodule policy.
255    ///
256    /// # Errors
257    ///
258    /// Returns [`RepositoryError::RequiresWorkTree`] in a bare repository, and work-tree I/O,
259    /// ODB, pathspec and rename detection errors.
260    pub fn tree_to_worktree(
261        &self,
262        tree: Option<&ObjectId>,
263        index: &Index,
264        options: &TreeDiffOptions,
265    ) -> Result<DiffEntriesResult> {
266        let work_tree = self.work_tree()?;
267        let config = self.repo.config().snapshot()?;
268        let restrict_to_paths = crate::diff::changes::pathspec_restrict_paths_for_scan(
269            self.repo,
270            index,
271            options.pathspec_specs(),
272            tree,
273        )?;
274        let mut entries = diff_tree_to_worktree_with_git_dir_and_rules_extras(
275            self.repo.odb(),
276            tree,
277            work_tree,
278            self.repo.git_dir(),
279            index,
280            Some(config.as_ref()),
281            None,
282            DiffTreeToWorktreeExtras {
283                restrict_to_paths,
284                ..DiffTreeToWorktreeExtras::default()
285            },
286        )?;
287        self.retain_pathspec(&mut entries, options)?;
288        retain_submodule_entries(&mut entries, options.submodules);
289        let worktree = DiffPostprocessWorktree { index };
290        self.pair_with_tree_sources(entries, tree, Some(work_tree), Some(&worktree), options)
291    }
292
293    /// Apply the rename, copy and break pairing of `options` to entries listed elsewhere.
294    ///
295    /// Old sides are read from the object database; a new side with a null `new_oid` is read
296    /// from the work tree. The pathspec, prefix and submodule fields of `options` are not used.
297    ///
298    /// # Parameters
299    ///
300    /// - `entries` - changed paths to pair, e.g. a filtered [`Self::tree_to_tree`] result.
301    /// - `source_tree` - with
302    ///   [`CopyDetection::FindHarder`](crate::diff::CopyDetection::FindHarder), every blob in
303    ///   this tree is a copy source as well; `None` limits sources to `entries`.
304    /// - `options` - rename, copy and break pairing and thread limits.
305    ///
306    /// # Errors
307    ///
308    /// Propagates object and work-tree reads while scoring pairs.
309    pub fn detect_renames(
310        &self,
311        entries: Vec<DiffEntry>,
312        source_tree: Option<&ObjectId>,
313        options: &TreeDiffOptions,
314    ) -> Result<DiffEntriesResult> {
315        self.pair_with_tree_sources(entries, source_tree, self.repo.work_tree(), None, options)
316    }
317
318    /// Staged, unstaged, and working-tree diffs over the repository's on-disk index.
319    ///
320    /// # Errors
321    ///
322    /// Returns index read errors.
323    pub fn uncommitted(&self) -> Result<UncommittedDiff<'repo>> {
324        let index = self.repo.load_index_preserving_sparse()?;
325        Ok(UncommittedDiff::new(self.repo, index))
326    }
327
328    /// Changed paths for `target`, limited to `pathspecs` and to the statuses in
329    /// `options.filter` (`--diff-filter`), sorted by path. No contents are loaded.
330    ///
331    /// Commit and tree targets diff stored trees without reading the index. Targets that read
332    /// the index or working tree load it once here; when their contents are needed next, call
333    /// [`UncommittedDiff::entries`] on [`Self::uncommitted`] instead and load them with
334    /// [`UncommittedDiff::load_worktree_changes`] or [`Self::object_changes`] on the same
335    /// handle.
336    ///
337    /// # Parameters
338    ///
339    /// - `target` - what to compare, e.g. from [`Self::resolve_request`].
340    /// - `pathspec` - repository-relative pathspecs; an entire-tree pathspec means every path.
341    /// - `options` - only `renames` and `filter` are used.
342    ///
343    /// # Errors
344    ///
345    /// Returns object read, rename detection, and pathspec errors, plus
346    /// [`RepositoryError::RequiresWorkTree`] for a working-tree target in a bare repository.
347    pub fn entries(
348        &self,
349        target: &DiffTarget,
350        pathspec: &Pathspec,
351        options: &DiffOptions,
352    ) -> Result<DiffEntriesResult> {
353        let specs = pathspec.specs();
354        match stored_target_entries(self.repo, target, specs, options)? {
355            Some(result) => limit_target_entries(self.repo, result, specs, options),
356            None => self.uncommitted()?.entries(target, pathspec, options),
357        }
358    }
359
360    /// Structured per-file diffs for `target`, honoring `pathspecs` and line-diff `opts`.
361    ///
362    /// # Errors
363    ///
364    /// Propagates index, ODB, and worktree diff failures.
365    pub fn files(
366        &self,
367        target: &DiffTarget,
368        pathspec: &Pathspec,
369        opts: &DiffOptions,
370    ) -> Result<Vec<FileDiff>> {
371        collect_files_for_target(self.repo, target, pathspec.specs(), opts.clone())
372    }
373
374    /// Per-file diffs at `detail` for entries from a metadata diff.
375    ///
376    /// Applies [`DiffOptions::renames`] to the entries first (Git's default `-M50`); pass
377    /// [`RenameDetection::Off`](crate::diff::RenameDetection::Off) when the entries are already
378    /// paired. [`DiffDetail::NameOnly`] and [`DiffDetail::NameStatus`] load no contents;
379    /// [`DiffDetail::Stat`] counts lines and [`DiffDetail::Patch`] builds hunks, in parallel
380    /// when the repository's thread policy allows.
381    ///
382    /// # Errors
383    ///
384    /// Propagates object database and parallel diff errors.
385    pub fn files_for_entries(
386        &self,
387        entries: Vec<DiffEntry>,
388        detail: DiffDetail,
389        options: &DiffOptions,
390    ) -> Result<DiffFilesOutput> {
391        let config = self.repo.config().snapshot()?;
392        crate::diff::files::build_file_diffs(
393            self.repo.odb(),
394            entries,
395            detail,
396            options.clone(),
397            config.as_ref(),
398            &self.repo.thread_policy(),
399        )
400    }
401
402    /// Patch rows for `entries` one file at a time, without retaining every hunk list.
403    ///
404    /// Like [`Self::files_for_entries`] at [`DiffDetail::Patch`], but `emit` receives each
405    /// file in path order and peak memory stays near one file's diff.
406    ///
407    /// # Errors
408    ///
409    /// Propagates object database, parallel diff and `emit` errors.
410    pub fn for_each_file(
411        &self,
412        entries: Vec<DiffEntry>,
413        options: &DiffOptions,
414        emit: impl FnMut(ListedFileDiff) -> Result<()>,
415    ) -> Result<()> {
416        let config = self.repo.config().snapshot()?;
417        crate::diff::files::build_file_diffs_streaming(
418            self.repo.odb(),
419            entries,
420            options.clone(),
421            config.as_ref(),
422            &self.repo.thread_policy(),
423            emit,
424        )
425    }
426
427    /// Diffstat (per-file insertions and deletions) for `entries`.
428    ///
429    /// Same rename handling as [`Self::files_for_entries`] at [`DiffDetail::Stat`].
430    ///
431    /// # Errors
432    ///
433    /// Propagates object database and parallel diff errors.
434    pub fn stat(&self, entries: Vec<DiffEntry>, options: &DiffOptions) -> Result<DiffStat> {
435        let output = self.files_for_entries(entries, DiffDetail::Stat, options)?;
436        Ok(DiffStat::from_files(&output.files))
437    }
438
439    /// Structured hunks for every entry, in input order, computed in parallel when the
440    /// repository's thread policy allows. Entries are used as given (no rename pairing).
441    ///
442    /// # Errors
443    ///
444    /// Propagates object database and parallel diff errors.
445    pub fn structured(
446        &self,
447        entries: Vec<DiffEntry>,
448        options: &DiffOptions,
449    ) -> Result<Vec<TreeDiffStructured>> {
450        let config = self.repo.config().snapshot()?;
451        crate::diff::tree_content::tree_diff_structured_parallel(
452            self.repo.odb(),
453            entries,
454            config.as_ref(),
455            &self.repo.thread_policy(),
456            options.clone(),
457        )
458    }
459
460    /// Like [`Self::structured`], but hands each file to `visit` in input order instead of
461    /// collecting them, so only a bounded window of results is held at once.
462    ///
463    /// # Errors
464    ///
465    /// Propagates object database, parallel diff and `visit` errors.
466    pub fn for_each_structured(
467        &self,
468        entries: &[DiffEntry],
469        options: &DiffOptions,
470        visit: impl FnMut(TreeDiffStructured) -> Result<()>,
471    ) -> Result<()> {
472        let config = self.repo.config().snapshot()?;
473        crate::diff::tree_content::for_each_tree_diff_structured(
474            self.repo.odb(),
475            entries,
476            options.clone(),
477            config.as_ref(),
478            &self.repo.thread_policy(),
479            visit,
480        )
481    }
482
483    /// Per-file diffs for one commit against its parents (Git `show` / `log -p` for a commit).
484    ///
485    /// A root commit is compared with the empty tree. A merge (two or more effective parents,
486    /// after grafts and shallow boundaries) is diffed per `merges`.
487    ///
488    /// # Parameters
489    ///
490    /// - `commit` - the commit to show.
491    /// - `merges` - how merge commits are diffed.
492    /// - `detail` - how much to compute per changed file.
493    /// - `options` - line-diff and rename settings.
494    /// - `pathspec` - paths to keep; an entire-tree pathspec keeps every path.
495    ///
496    /// # Errors
497    ///
498    /// Propagates object read, tree diff, pathspec and parallel diff errors.
499    pub fn commit_files(
500        &self,
501        commit: &ObjectId,
502        merges: DiffMerges,
503        detail: DiffDetail,
504        options: &DiffOptions,
505        pathspec: &Pathspec,
506    ) -> Result<DiffFilesOutput> {
507        crate::diff::merge_commit::commit_diff_files(
508            self.repo,
509            commit,
510            merges,
511            detail,
512            options,
513            pathspec,
514            &self.repo.thread_policy(),
515        )
516    }
517
518    /// Load old and new contents for entries that compare stored objects (trees, commits or
519    /// the index against a tree), in parallel when the thread policy allows.
520    ///
521    /// Work-tree entries need [`UncommittedDiff::load_worktree_changes`] instead.
522    ///
523    /// # Errors
524    ///
525    /// Propagates object read errors.
526    pub fn object_changes(&self, entries: &[DiffEntry]) -> Result<Vec<FileChange>> {
527        crate::diff::changes::load_object_changes(self.repo, entries)
528    }
529
530    /// Unstaged file diffs for `pathspec` plus the hunks other paths share with them, the
531    /// input for hunk-level staging by [`HunkId`](crate::diff::HunkId).
532    ///
533    /// # Errors
534    ///
535    /// Returns [`RepositoryError::RequiresWorkTree`] in a bare repository, and index, ODB and
536    /// work-tree diff errors.
537    pub fn hunk_bundle(
538        &self,
539        pathspec: &Pathspec,
540        options: &DiffOptions,
541    ) -> Result<HunkDiffBundle> {
542        crate::diff::targets::hunk_diff_bundle(self.repo, pathspec, options.clone())
543    }
544
545    /// Turn a user's diff request (staged/unstaged flags, revisions and paths) into a
546    /// [`DiffTarget`] and resolved pathspecs.
547    ///
548    /// # Parameters
549    ///
550    /// - `cwd_prefix` - work-tree-relative directory the paths are relative to.
551    /// - `request` - what the user asked for.
552    ///
553    /// # Errors
554    ///
555    /// Returns [`DiffError::Arguments`](crate::error::DiffError::Arguments) with a
556    /// [`ResolveDiffArgumentsError`](crate::diff::ResolveDiffArgumentsError) for conflicting flags, unknown or non-commit revisions,
557    /// bad pathspecs, and work-tree targets in a bare repository, plus revision errors such as
558    /// [`RevisionError::NoMergeBase`](crate::error::RevisionError::NoMergeBase) for ranges.
559    pub fn resolve_request(
560        &self,
561        cwd_prefix: Option<&str>,
562        request: &DiffRequest,
563    ) -> Result<DiffArguments> {
564        crate::diff::targets::resolve_diff_request(self.repo, cwd_prefix, request)
565    }
566
567    /// Resolve pathspecs that limit a commit diff (`show`, `log -p`), also in a bare
568    /// repository, where they are relative to the repository root.
569    ///
570    /// # Errors
571    ///
572    /// Returns [`DiffError::Arguments`](crate::error::DiffError::Arguments) with a
573    /// [`ResolveDiffArgumentsError`](crate::diff::ResolveDiffArgumentsError) for pathspecs outside the repository or with invalid
574    /// magic.
575    pub fn resolve_pathspec(
576        &self,
577        cwd_prefix: Option<&str>,
578        raw_paths: &[String],
579    ) -> Result<Pathspec> {
580        crate::diff::targets::resolve_commit_diff_pathspecs(self.repo, cwd_prefix, raw_paths)
581    }
582
583    fn work_tree(&self) -> Result<&'repo Path> {
584        Ok(self
585            .repo
586            .work_tree()
587            .ok_or(RepositoryError::RequiresWorkTree)?)
588    }
589
590    fn thread_policy(&self, options: &TreeDiffOptions) -> ThreadPolicy {
591        options.threads.unwrap_or_else(|| self.repo.thread_policy())
592    }
593
594    fn matcher<'s>(&self, options: &'s TreeDiffOptions) -> Result<Option<PathspecMatcher<'s>>> {
595        let Some(pathspec) = options.pathspec.as_ref() else {
596            return Ok(None);
597        };
598        if pathspec.specs().is_empty() {
599            return Ok(None);
600        }
601        Ok(Some(self.repo.pathspec_matcher_with_globals(
602            pathspec.specs(),
603            pathspec.globals(),
604        )?))
605    }
606
607    fn retain_pathspec(
608        &self,
609        entries: &mut Vec<DiffEntry>,
610        options: &TreeDiffOptions,
611    ) -> Result<()> {
612        if let Some(matcher) = self.matcher(options)? {
613            entries.retain(|entry| matcher.matches_change(entry.path(), entry.old_path.as_deref()));
614        }
615        Ok(())
616    }
617
618    /// Pair `entries` per `options`, with the blobs of `source_tree` as copy sources.
619    fn pair_with_tree_sources(
620        &self,
621        entries: Vec<DiffEntry>,
622        source_tree: Option<&ObjectId>,
623        work_root: Option<&Path>,
624        worktree: Option<&DiffPostprocessWorktree<'_>>,
625        options: &TreeDiffOptions,
626    ) -> Result<DiffEntriesResult> {
627        if !needs_postprocess(&entries, options) {
628            return self.pair_with_sources(entries, &[], work_root, worktree, false, options);
629        }
630        let config = self.repo.config().snapshot()?;
631        let mut notice = None;
632        let source_tree = source_tree.filter(|_| options.copies != crate::diff::CopyDetection::Off);
633        let entries = postprocess_diff_entries(
634            self.repo.odb(),
635            entries,
636            source_tree,
637            work_root,
638            worktree,
639            config.as_ref(),
640            &self.thread_policy(options),
641            &options.postprocess_options(worktree.is_some()),
642            Some(&mut notice),
643        )?;
644        Ok(DiffEntriesResult {
645            entries,
646            inexact_rename_skipped: notice,
647            ..DiffEntriesResult::default()
648        })
649    }
650
651    /// Pair `entries` per `options`, with `sources` as the extra copy sources.
652    fn pair_with_sources(
653        &self,
654        entries: Vec<DiffEntry>,
655        sources: &[(String, FileMode, ObjectId)],
656        work_root: Option<&Path>,
657        worktree: Option<&DiffPostprocessWorktree<'_>>,
658        materialize_worktree_oid: bool,
659        options: &TreeDiffOptions,
660    ) -> Result<DiffEntriesResult> {
661        if entries.is_empty() || !options.pairs_entries() {
662            return Ok(DiffEntriesResult::new(entries));
663        }
664        let config = self.repo.config().snapshot()?;
665        let thread_policy = self.thread_policy(options);
666        if !needs_postprocess(&entries, options) {
667            let Some(threshold) = options.renames.threshold_percent() else {
668                return Ok(DiffEntriesResult::new(entries));
669            };
670            let out = detect_renames_with_policy(
671                self.repo.odb(),
672                work_root,
673                entries,
674                threshold,
675                config.as_ref(),
676                &thread_policy,
677                None,
678                DetectRenamesOptions::default(),
679            )?;
680            return Ok(DiffEntriesResult {
681                entries: out.entries,
682                inexact_rename_skipped: out.inexact_skipped,
683                ..DiffEntriesResult::default()
684            });
685        }
686        let mut notice = None;
687        let entries = postprocess_diff_entries_from_sources(
688            self.repo.odb(),
689            entries,
690            sources,
691            work_root,
692            worktree,
693            config.as_ref(),
694            &thread_policy,
695            &options.postprocess_options(materialize_worktree_oid),
696            Some(&mut notice),
697        )?;
698        Ok(DiffEntriesResult {
699            entries,
700            inexact_rename_skipped: notice,
701            ..DiffEntriesResult::default()
702        })
703    }
704}
705
706/// Copy and break pairing go through the post-processing pipeline; renames alone pair
707/// directly, so `-M100` (exact renames only) keeps its meaning.
708fn needs_postprocess(entries: &[DiffEntry], options: &TreeDiffOptions) -> bool {
709    !entries.is_empty()
710        && (options.copies != crate::diff::CopyDetection::Off
711            || options.break_rewrites != crate::diff::BreakRewrites::Off)
712}
713
714/// Drop changes whose every present side is a gitlink when submodules are ignored entirely.
715fn retain_submodule_entries(entries: &mut Vec<DiffEntry>, submodules: SubmoduleIgnoreMode) {
716    if submodules != SubmoduleIgnoreMode::All {
717        return;
718    }
719    entries.retain(|entry| {
720        let gitlink_or_absent = |mode: FileMode| mode.is_gitlink() || mode == FileMode::ABSENT;
721        !(gitlink_or_absent(entry.old_mode) && gitlink_or_absent(entry.new_mode))
722    });
723}
724
725impl<'repo> Diff<'repo> {
726    /// Attribute each line of a worktree path to a commit (blame).
727    ///
728    /// # Errors
729    ///
730    /// Propagates blame resolution, object read, and worktree failures documented on
731    /// [`crate::blame::blame_file`].
732    pub fn blame(
733        &self,
734        path: &str,
735        options: &crate::blame::BlameOptions,
736    ) -> Result<crate::blame::BlameResult> {
737        crate::blame::blame_file(self.repo, path, options)
738    }
739
740    /// Resolve a Git-style `-L` range for blame on `path` at a fixed start commit.
741    pub fn resolve_blame_line_range(
742        &self,
743        start: ObjectId,
744        path: &str,
745        spec: &str,
746    ) -> std::result::Result<std::ops::RangeInclusive<usize>, crate::line_range::LineRangeError>
747    {
748        crate::blame::resolve_blame_line_range(self.repo, start, path, spec)
749    }
750
751    /// Resolve a Git-style `-L` range using full [`crate::blame::BlameOptions`].
752    pub fn resolve_blame_line_range_with_options(
753        &self,
754        path: &str,
755        spec: &str,
756        options: &crate::blame::BlameOptions,
757    ) -> std::result::Result<std::ops::RangeInclusive<usize>, crate::line_range::LineRangeError>
758    {
759        crate::blame::resolve_blame_line_range_with_options(self.repo, path, spec, options)
760    }
761}