Skip to main content

grit_lib/diff/
changes.rs

1//! Staged, unstaged, and working-tree changes with both sides' contents loaded.
2//!
3//! [`UncommittedDiff`] collects [`DiffEntry`] rows for the index against `HEAD`, the working
4//! tree against the index, or the working tree against any tree, reusing one loaded index and
5//! one set of [`WorktreeRules`] for every step; [`UncommittedDiff::entries`] picks the comparison
6//! from a [`DiffTarget`] and applies pathspecs and `--diff-filter`.
7//! [`UncommittedDiff::load_worktree_changes`] and
8//! [`Diff::object_changes`](super::Diff::object_changes) then turn entries into [`FileChange`]s whose bytes feed structured
9//! hunks ([`FileChange::structured`]) or line counts ([`FileChange::line_stat`]).
10
11use std::collections::{BTreeSet, HashSet};
12use std::path::Path;
13use std::sync::{Arc, Mutex};
14
15use crate::diff::structured::{structured_file_diff, SideBytes, StructuredFileDiff};
16use crate::diff::targets::{
17    diff_index_to_tree_for_paths, limit_target_entries, stored_target_entries,
18};
19use crate::diff::tree_content::{gitlink_line, load_new_side, load_old_side};
20use crate::diff::{
21    apply_rename_detection_to_diff_entries, diff_index_to_tree_with_renames,
22    diff_index_to_worktree_with_renames, diff_tree_to_worktree_with_git_dir_and_rules_extras,
23    index_mtime_for_diff, load_worktree_side_for_diff, peer_scope_includes_path,
24    read_submodule_head_oid, sort_entries_by_path, submodule_porcelain_flags, DiffEntry,
25    DiffIndexToWorktreeOptions, DiffOptions, DiffSide, DiffStatus, DiffTarget,
26    DiffTreeToWorktreeExtras, LineStat, RenameDetection, RENAME_DETECTION_DISABLED,
27};
28use crate::error::Result;
29use crate::index::write_tree::cache_tree_extension_valid;
30use crate::index::Index;
31use crate::objects::odb::Odb;
32use crate::objects::{FileMode, ObjectId};
33use crate::parallel::{try_par_map, ParallelHashError, ParallelOp};
34use crate::repo::Repository;
35use crate::repo::RepositoryError;
36use crate::state::resolve_head_for_repository;
37use crate::worktree::fsmonitor::fsmonitor_enabled;
38use crate::worktree::worktree_rules::WorktreeRules;
39
40/// One changed path with both sides' bytes loaded for diffing.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct FileChange {
43    /// Display path (new path, or old path for a deletion).
44    pub path: String,
45    /// Pre-rename path, only when it differs from [`Self::path`].
46    pub old_path: Option<String>,
47    /// Change kind for this path.
48    pub status: DiffStatus,
49    /// Old side mode ([`FileMode::ABSENT`] when the path is added).
50    pub old_mode: FileMode,
51    /// New side mode ([`FileMode::ABSENT`] when the path is deleted).
52    pub new_mode: FileMode,
53    /// Old side object id (zero when absent).
54    pub old_oid: ObjectId,
55    /// New side object id (zero when absent or not yet hashed from the working tree).
56    pub new_oid: ObjectId,
57    /// Old side contents (a `Subproject commit` line for gitlinks).
58    pub old_bytes: SideBytes,
59    /// New side contents, read from the working tree for working-tree changes.
60    pub new_bytes: SideBytes,
61    /// Either side is treated as binary; a binary change may carry neither side's bytes.
62    pub binary: bool,
63    /// The object ids differ (false for a mode-only change).
64    pub content_changed: bool,
65    /// Rename or copy similarity (0–100), when applicable.
66    pub similarity: Option<u32>,
67}
68
69impl FileChange {
70    fn from_entry(
71        entry: DiffEntry,
72        old_bytes: SideBytes,
73        new_bytes: SideBytes,
74        binary: bool,
75    ) -> Self {
76        let path = entry
77            .new_path
78            .clone()
79            .or_else(|| entry.old_path.clone())
80            .unwrap_or_default();
81        let similarity = entry.rename_similarity();
82        // A deletion's display path is its old path; only a real rename keeps `old_path`.
83        let old_path = entry.old_path.filter(|old| *old != path);
84        Self {
85            path,
86            old_path,
87            status: entry.status,
88            old_mode: entry.old_mode,
89            new_mode: entry.new_mode,
90            old_oid: entry.old_oid,
91            new_oid: entry.new_oid,
92            old_bytes,
93            new_bytes,
94            binary,
95            content_changed: entry.old_oid != entry.new_oid,
96            similarity,
97        }
98    }
99
100    /// Structured line hunks and mode metadata for this change.
101    ///
102    /// Binary changes get mode metadata and no hunks.
103    ///
104    /// # Parameters
105    ///
106    /// - `options` - line-diff settings (context, algorithm, whitespace handling).
107    #[must_use]
108    pub fn structured(&self, options: DiffOptions) -> StructuredFileDiff {
109        if self.binary {
110            return StructuredFileDiff {
111                old_mode: self.old_mode.octal_if_present(),
112                new_mode: self.new_mode.octal_if_present(),
113                old_encoding_lossy: self.old_bytes.encoding_lossy,
114                new_encoding_lossy: self.new_bytes.encoding_lossy,
115                hunks: Vec::new(),
116            };
117        }
118        structured_file_diff(
119            self.old_mode,
120            self.new_mode,
121            &self.old_bytes,
122            &self.new_bytes,
123            options,
124        )
125    }
126
127    /// Inserted and deleted line counts, or `None` for a binary change.
128    ///
129    /// # Parameters
130    ///
131    /// - `options` - line-diff settings; whitespace modes change what counts as a changed line.
132    #[must_use]
133    pub fn line_stat(&self, options: &DiffOptions) -> Option<LineStat> {
134        if self.binary {
135            return None;
136        }
137        Some(super::detail::line_stat_for_options(
138            &self.old_bytes.text(),
139            &self.new_bytes.text(),
140            options,
141        ))
142    }
143}
144
145/// Load both sides of each entry from the object database.
146///
147/// Use this for index-against-tree and tree-against-tree entries, whose sides are all stored
148/// objects. Entries are loaded in parallel per the repository's thread policy; the result keeps
149/// the order of `entries`.
150///
151/// # Parameters
152///
153/// - `repo` - repository whose object database holds both sides.
154/// - `entries` - diff rows to load, e.g. from [`UncommittedDiff::staged_entries`].
155///
156/// # Errors
157///
158/// Returns config load failures and object read errors.
159pub(crate) fn load_object_changes(
160    repo: &Repository,
161    entries: &[DiffEntry],
162) -> Result<Vec<FileChange>> {
163    let config = repo.config().snapshot()?;
164    let par_opts = repo
165        .thread_policy()
166        .resolve(ParallelOp::DiffContent, config.as_ref());
167    let odb = repo.odb();
168    let est_bytes = entries.len().saturating_mul(8192);
169    try_par_map(entries, par_opts, est_bytes, |entry| {
170        load_change(odb, entry.clone(), None)
171    })
172    .map_err(|ParallelHashError::Task(err)| err)
173}
174
175/// Where a working-tree change's new side is read from.
176pub(crate) struct WorktreeSide<'a> {
177    pub(crate) work_tree: &'a Path,
178    pub(crate) index: &'a Index,
179    pub(crate) rules: &'a Mutex<WorktreeRules>,
180}
181
182/// Load one entry's sides: the old side from the object database, the new side from the
183/// working tree when `worktree` is given, otherwise from the object database.
184///
185/// A binary new side makes the whole change binary, so the old blob is then not read at all.
186pub(crate) fn load_change(
187    odb: &Odb,
188    entry: DiffEntry,
189    worktree: Option<&WorktreeSide<'_>>,
190) -> Result<FileChange> {
191    let (new_bytes, new_binary) = match worktree {
192        Some(side) => load_worktree_new_side(odb, &entry, side)?,
193        None => load_new_side(odb, &entry)?,
194    };
195    let (old_bytes, old_binary) = if new_binary {
196        (old_side_without_payload(odb, &entry, worktree)?, false)
197    } else {
198        load_old_side(odb, &entry)?
199    };
200    Ok(FileChange::from_entry(
201        entry,
202        old_bytes,
203        new_bytes,
204        old_binary || new_binary,
205    ))
206}
207
208/// Load every entry with [`load_change`], in order.
209pub(crate) fn load_changes(
210    odb: &Odb,
211    entries: Vec<DiffEntry>,
212    worktree: Option<&WorktreeSide<'_>>,
213) -> Result<Vec<FileChange>> {
214    entries
215        .into_iter()
216        .map(|entry| load_change(odb, entry, worktree))
217        .collect()
218}
219
220fn old_side_without_payload(
221    odb: &Odb,
222    entry: &DiffEntry,
223    worktree: Option<&WorktreeSide<'_>>,
224) -> Result<SideBytes> {
225    if entry.old_mode == FileMode::GITLINK {
226        return Ok(SideBytes::from_bytes(
227            gitlink_line(&entry.old_oid).into_bytes(),
228        ));
229    }
230    if entry.old_mode == FileMode::ABSENT {
231        return Ok(SideBytes::unread(0));
232    }
233    if let Some(side) = worktree {
234        if let Some(path) = entry.old_path.as_deref().or(entry.new_path.as_deref()) {
235            if let Some(ie) = side.index.get(&crate::repo_relpath::storage_bytes(path), 0) {
236                if ie.oid == entry.old_oid && !ie.stat_cache_unset() {
237                    return Ok(SideBytes::unread(u64::from(ie.size)));
238                }
239            }
240        }
241    }
242    if entry.old_oid.is_zero() {
243        return Ok(SideBytes::unread(0));
244    }
245    let info = odb.read_info(&entry.old_oid)?;
246    Ok(SideBytes::unread(info.size))
247}
248
249fn load_worktree_new_side(
250    odb: &Odb,
251    entry: &DiffEntry,
252    side: &WorktreeSide<'_>,
253) -> Result<(SideBytes, bool)> {
254    if entry.new_mode == FileMode::GITLINK {
255        let line = worktree_gitlink_line(entry, side.work_tree);
256        return Ok((SideBytes::from_bytes(line.into_bytes()), false));
257    }
258    if entry.new_mode == FileMode::ABSENT {
259        return Ok((SideBytes::from_bytes(Vec::new()), false));
260    }
261    let Some(path) = entry.new_path.as_deref().or(entry.old_path.as_deref()) else {
262        return load_new_side(odb, entry);
263    };
264    // Working-tree entries often carry only a hash of the normalized file, and the blob is not
265    // in the object database until it is staged, so always read the live file.
266    let index_entry = side.index.get(&crate::repo_relpath::storage_bytes(path), 0);
267    let rules = side.rules.lock().unwrap_or_else(|e| e.into_inner());
268    load_worktree_side_for_diff(
269        odb,
270        side.work_tree,
271        path,
272        entry.new_mode.bits(),
273        rules.config(),
274        index_entry,
275        Some(&rules),
276        false,
277    )
278}
279
280/// The submodule's checked-out commit, with `-dirty` when its tracked content is modified.
281fn worktree_gitlink_line(entry: &DiffEntry, work_tree: &Path) -> String {
282    let path = entry.new_path.as_deref().or(entry.old_path.as_deref());
283    let head = if entry.new_oid != ObjectId::zero() {
284        Some(entry.new_oid)
285    } else {
286        path.and_then(|p| read_submodule_head_oid(&work_tree.join(p)))
287    };
288    let Some(head) = head.filter(|oid| *oid != ObjectId::zero()) else {
289        return String::new();
290    };
291    let dirty = entry.old_mode == FileMode::GITLINK
292        && path.is_some_and(|p| submodule_porcelain_flags(work_tree, p, entry.old_oid).modified);
293    if dirty {
294        format!("Subproject commit {}-dirty\n", head.to_hex())
295    } else {
296        gitlink_line(&head)
297    }
298}
299
300/// Paths to scan before a worktree or index diff when `pathspecs` limit the operation.
301///
302/// Includes index entries selected by the pathspecs plus blob paths in `base_tree` that match,
303/// so a staged deletion (absent from the index but present in `HEAD`) is not dropped.
304pub(crate) fn pathspec_restrict_paths_for_scan(
305    repo: &Repository,
306    index: &Index,
307    pathspecs: &[String],
308    base_tree: Option<&ObjectId>,
309) -> Result<Option<Arc<BTreeSet<String>>>> {
310    if pathspecs.is_empty() {
311        return Ok(None);
312    }
313    let base_ctx = repo.pathspec_match_context();
314    let mut paths = crate::porcelain::add::restricted_index_paths_for_pathspecs(
315        repo, index, pathspecs, base_ctx,
316    )?;
317    if let Some(tree) = base_tree {
318        let attr_matcher = if pathspecs
319            .iter()
320            .any(|s| crate::pathspec::pathspec_has_attr_magic(s))
321        {
322            Some(repo.pathspec_matcher(pathspecs)?)
323        } else {
324            None
325        };
326        for (path, mode, _) in super::flatten_tree_entries(repo.odb(), tree)? {
327            if crate::porcelain::add::blob_path_matches_restrict_pathspecs(
328                &path,
329                mode.bits(),
330                pathspecs,
331                base_ctx,
332                attr_matcher.as_ref(),
333            )? {
334                paths.insert(path);
335            }
336        }
337    }
338    Ok(Some(Arc::new(paths)))
339}
340
341fn rename_threshold(renames: RenameDetection) -> u32 {
342    renames
343        .threshold_percent()
344        .unwrap_or(RENAME_DETECTION_DISABLED)
345}
346
347/// Index against `HEAD`'s tree, sorted by path.
348///
349/// A non-empty `restrict_to_paths` compares only those exact paths, without rename detection.
350pub(crate) fn staged_entries_in(
351    repo: &Repository,
352    index: &Index,
353    rename_threshold: u32,
354    restrict_to_paths: Option<&BTreeSet<String>>,
355) -> Result<Vec<DiffEntry>> {
356    let head_tree = resolve_head_for_repository(repo)?.tree(repo.odb())?;
357    let config = repo.config().snapshot()?;
358    let mut entries = match restrict_to_paths.filter(|paths| !paths.is_empty()) {
359        Some(paths) => diff_index_to_tree_for_paths(repo, index, head_tree.as_ref(), paths)?,
360        None => diff_index_to_tree_with_renames(
361            repo.odb(),
362            index,
363            head_tree.as_ref(),
364            false,
365            rename_threshold,
366            config.as_ref(),
367            &repo.thread_policy(),
368        )?,
369    };
370    if let Some(work_tree) = repo.work_tree() {
371        entries.retain(|entry| {
372            if !entry.old_mode.is_gitlink() && !entry.new_mode.is_gitlink() {
373                return true;
374            }
375            let Some(path) = entry.new_path.as_deref().or(entry.old_path.as_deref()) else {
376                return true;
377            };
378            !crate::submodule_ignore::staged_gitlink_omitted_in_diff(
379                config.as_ref(),
380                work_tree,
381                path,
382            )
383        });
384    }
385    sort_entries_by_path(&mut entries);
386    Ok(entries)
387}
388
389/// Working tree against `index`, sorted by path.
390///
391/// `restrict_to_paths` limits the scan to those paths and skips the fsmonitor refresh. A file
392/// whose size changed (under an identity clean conversion) is reported without being hashed,
393/// with a null `new_oid`; loading its side reads the live file anyway.
394pub(crate) fn unstaged_entries_in(
395    repo: &Repository,
396    index: &mut Index,
397    work_tree: &Path,
398    rules: &Arc<Mutex<WorktreeRules>>,
399    rename_threshold: u32,
400    restrict_to_paths: Option<Arc<BTreeSet<String>>>,
401) -> Result<Vec<DiffEntry>> {
402    let config = rules.lock().unwrap_or_else(|e| e.into_inner()).config_arc();
403    let refresh_fsmonitor = restrict_to_paths.is_none() && fsmonitor_enabled(config.as_ref());
404    let options = DiffIndexToWorktreeOptions {
405        repository_git_dir: Some(repo.git_dir().to_path_buf()),
406        index_mtime: index_mtime_for_diff(index, None),
407        config: Some(config),
408        thread_policy: Some(repo.thread_policy()),
409        refresh_index_stat_in_pass: false,
410        size_change_proves_modified: true,
411        refresh_fsmonitor,
412        worktree_rules: Some(Arc::clone(rules)),
413        command_runner: Some(repo.command_runner()),
414        restrict_to_paths,
415        skip_inaccessible_paths: true,
416        diagnostics: Some(repo.diagnostics()),
417        ..DiffIndexToWorktreeOptions::default()
418    };
419    let (mut entries, _) =
420        diff_index_to_worktree_with_renames(repo, index, work_tree, options, rename_threshold)?;
421    sort_entries_by_path(&mut entries);
422    Ok(entries)
423}
424
425/// Working tree (through `index`) against `base_tree`, sorted by path.
426///
427/// When the index's cache tree matches `base_tree`, this is the cheaper index-against-worktree
428/// scan; otherwise the tree is walked against the working tree directly.
429pub(crate) fn worktree_entries_in(
430    repo: &Repository,
431    index: &mut Index,
432    work_tree: &Path,
433    rules: &Arc<Mutex<WorktreeRules>>,
434    base_tree: Option<&ObjectId>,
435    rename_threshold: u32,
436    restrict_to_paths: Option<Arc<BTreeSet<String>>>,
437) -> Result<Vec<DiffEntry>> {
438    let index_matches_base = match (base_tree, index.cache_tree_root.as_ref()) {
439        (Some(base), Some(cached)) => base == cached,
440        (None, None) => true,
441        _ => false,
442    };
443    if index_matches_base && cache_tree_extension_valid(index.cache_tree.as_ref()) {
444        return unstaged_entries_in(
445            repo,
446            index,
447            work_tree,
448            rules,
449            rename_threshold,
450            restrict_to_paths,
451        );
452    }
453    let config = repo.config().snapshot()?;
454    let raw = {
455        let rules = rules.lock().unwrap_or_else(|e| e.into_inner());
456        diff_tree_to_worktree_with_git_dir_and_rules_extras(
457            repo.odb(),
458            base_tree,
459            work_tree,
460            repo.git_dir(),
461            index,
462            Some(config.as_ref()),
463            Some(&rules),
464            DiffTreeToWorktreeExtras {
465                skip_inaccessible_paths: true,
466                diagnostics: Some(repo.diagnostics()),
467                restrict_to_paths: restrict_to_paths.clone(),
468            },
469        )?
470    };
471    let mut entries = apply_rename_detection_to_diff_entries(
472        repo.odb(),
473        raw,
474        Some(work_tree),
475        rename_threshold,
476        config.as_ref(),
477        &repo.thread_policy(),
478    )?;
479    sort_entries_by_path(&mut entries);
480    Ok(entries)
481}
482
483/// Staged, unstaged, and working-tree diffs over one loaded index.
484///
485/// Every method reuses the same [`Index`] and, once a working-tree method needs them, the same
486/// [`WorktreeRules`], so collecting entries and then loading their contents reads neither twice.
487/// Working-tree scans may refresh stat data on the in-memory index; nothing is written to disk.
488///
489/// Obtain one from [`Diff::uncommitted`](crate::diff::Diff::uncommitted) or
490/// [`UncommittedDiff::new`].
491pub struct UncommittedDiff<'repo> {
492    repo: &'repo Repository,
493    index: Index,
494    rules: Option<Arc<Mutex<WorktreeRules>>>,
495}
496
497impl<'repo> UncommittedDiff<'repo> {
498    /// Diff `repo` against an index the caller already loaded.
499    ///
500    /// # Parameters
501    ///
502    /// - `repo` - repository to diff.
503    /// - `index` - its index (normally the on-disk index).
504    #[must_use]
505    pub fn new(repo: &'repo Repository, index: Index) -> Self {
506        Self {
507            repo,
508            index,
509            rules: None,
510        }
511    }
512
513    /// The index every comparison uses.
514    #[must_use]
515    pub fn index(&self) -> &Index {
516        &self.index
517    }
518
519    /// Index against `HEAD`'s tree (`grit diff --staged`), sorted by path.
520    ///
521    /// An unborn `HEAD` compares against the empty tree, so every index entry is added.
522    ///
523    /// # Parameters
524    ///
525    /// - `renames` - rename detection between deleted and added paths.
526    ///
527    /// # Errors
528    ///
529    /// Returns `HEAD` resolution, config, and object read errors.
530    pub fn staged_entries(&self, renames: RenameDetection) -> Result<Vec<DiffEntry>> {
531        self.staged_entries_for_paths(renames, None)
532    }
533
534    fn staged_entries_for_paths(
535        &self,
536        renames: RenameDetection,
537        restrict_to_paths: Option<Arc<BTreeSet<String>>>,
538    ) -> Result<Vec<DiffEntry>> {
539        staged_entries_in(
540            self.repo,
541            &self.index,
542            rename_threshold(renames),
543            restrict_to_paths.as_deref(),
544        )
545    }
546
547    /// Working tree against the index (`grit diff --unstaged`), sorted by path.
548    ///
549    /// Like Git's `diff-files`, a working-tree side that was not hashed carries a null
550    /// `new_oid`; a tracked file whose size changed is reported that way without reading it.
551    ///
552    /// # Parameters
553    ///
554    /// - `renames` - rename detection between deleted and added paths.
555    ///
556    /// # Errors
557    ///
558    /// Returns [`RepositoryError::RequiresWorkTree`] in a bare repository, plus worktree rule, I/O, and
559    /// object read errors.
560    pub fn unstaged_entries(&mut self, renames: RenameDetection) -> Result<Vec<DiffEntry>> {
561        self.unstaged_entries_for_paths(renames, None)
562    }
563
564    fn unstaged_entries_for_paths(
565        &mut self,
566        renames: RenameDetection,
567        restrict_to_paths: Option<Arc<BTreeSet<String>>>,
568    ) -> Result<Vec<DiffEntry>> {
569        let work_tree = self.work_tree()?;
570        let rules = self.rules()?;
571        unstaged_entries_in(
572            self.repo,
573            &mut self.index,
574            work_tree,
575            &rules,
576            rename_threshold(renames),
577            restrict_to_paths,
578        )
579    }
580
581    /// Working tree and index together against `base_tree` (`grit diff`, `grit diff --against`),
582    /// sorted by path.
583    ///
584    /// # Parameters
585    ///
586    /// - `base_tree` - tree to compare with; `None` for the empty tree (an unborn `HEAD`).
587    /// - `renames` - rename detection between deleted and added paths.
588    ///
589    /// # Errors
590    ///
591    /// Returns [`RepositoryError::RequiresWorkTree`] in a bare repository, plus worktree rule, I/O, and
592    /// object read errors.
593    pub fn worktree_entries(
594        &mut self,
595        base_tree: Option<&ObjectId>,
596        renames: RenameDetection,
597    ) -> Result<Vec<DiffEntry>> {
598        self.worktree_entries_for_paths(base_tree, renames, None)
599    }
600
601    fn worktree_entries_for_paths(
602        &mut self,
603        base_tree: Option<&ObjectId>,
604        renames: RenameDetection,
605        restrict_to_paths: Option<Arc<BTreeSet<String>>>,
606    ) -> Result<Vec<DiffEntry>> {
607        let work_tree = self.work_tree()?;
608        let rules = self.rules()?;
609        worktree_entries_in(
610            self.repo,
611            &mut self.index,
612            work_tree,
613            &rules,
614            base_tree,
615            rename_threshold(renames),
616            restrict_to_paths,
617        )
618    }
619
620    /// Changed paths for any [`DiffTarget`], limited to `pathspecs` and to the statuses in
621    /// `options.filter` (`--diff-filter`), sorted by path. No contents are loaded.
622    ///
623    /// [`DiffTarget::WorktreeVsHead`] compares with `HEAD`'s tree (the empty tree when unborn).
624    /// Commit and tree targets ignore the index, so prefer [`Diff::entries`](crate::diff::Diff::entries)
625    /// for them; it does not load one.
626    ///
627    /// # Parameters
628    ///
629    /// - `target` - what to compare, e.g. from [`Diff::resolve_request`](crate::diff::Diff::resolve_request).
630    /// - `pathspecs` - repository-relative pathspecs; empty means every path.
631    /// - `options` - only `renames` and `filter` are used.
632    ///
633    /// # Errors
634    ///
635    /// Returns [`RepositoryError::RequiresWorkTree`] for a working-tree target in a bare repository, plus
636    /// `HEAD` resolution, pathspec, worktree rule, I/O, and object read errors.
637    pub fn entries(
638        &mut self,
639        target: &DiffTarget,
640        pathspec: &crate::pathspec::Pathspec,
641        options: &DiffOptions,
642    ) -> Result<super::core::DiffEntriesResult> {
643        let pathspecs = pathspec.specs();
644        let renames = options.renames;
645        let result = match target {
646            DiffTarget::IndexVsHead => {
647                let head_tree = resolve_head_for_repository(self.repo)?.tree(self.repo.odb())?;
648                let restrict = pathspec_restrict_paths_for_scan(
649                    self.repo,
650                    &self.index,
651                    pathspecs,
652                    head_tree.as_ref(),
653                )?;
654                super::core::DiffEntriesResult {
655                    entries: self.staged_entries_for_paths(renames, restrict)?,
656                    inexact_rename_skipped: None,
657                    ..Default::default()
658                }
659            }
660            DiffTarget::WorktreeVsIndex => {
661                let restrict =
662                    pathspec_restrict_paths_for_scan(self.repo, &self.index, pathspecs, None)?;
663                super::core::DiffEntriesResult {
664                    entries: self.unstaged_entries_for_paths(renames, restrict)?,
665                    inexact_rename_skipped: None,
666                    ..Default::default()
667                }
668            }
669            DiffTarget::WorktreeVsHead => {
670                let head_tree = resolve_head_for_repository(self.repo)?.tree(self.repo.odb())?;
671                let restrict = pathspec_restrict_paths_for_scan(
672                    self.repo,
673                    &self.index,
674                    pathspecs,
675                    head_tree.as_ref(),
676                )?;
677                super::core::DiffEntriesResult {
678                    entries: self.worktree_entries_for_paths(
679                        head_tree.as_ref(),
680                        renames,
681                        restrict,
682                    )?,
683                    ..Default::default()
684                }
685            }
686            DiffTarget::WorktreeVsTree(tree) => {
687                let restrict = pathspec_restrict_paths_for_scan(
688                    self.repo,
689                    &self.index,
690                    pathspecs,
691                    Some(tree),
692                )?;
693                super::core::DiffEntriesResult {
694                    entries: self.worktree_entries_for_paths(Some(tree), renames, restrict)?,
695                    inexact_rename_skipped: None,
696                    ..Default::default()
697                }
698            }
699            DiffTarget::Commit(_) | DiffTarget::Trees { .. } => {
700                stored_target_entries(self.repo, target, pathspecs, options)?.unwrap_or_default()
701            }
702        };
703        limit_target_entries(self.repo, result, pathspecs, options)
704    }
705
706    /// Changes on the other side of the index for the paths in `primary_paths`, which feed
707    /// [`hunk_ids`](crate::diff::hunk_ids) so hunk ids
708    /// stay stable when an identical hunk moves between the staged and unstaged sides.
709    ///
710    /// For [`DiffSide::Staged`] primaries this loads the unstaged changes on those paths; for
711    /// [`DiffSide::Unstaged`] the staged ones. [`DiffSide::Other`] has no peer side. A path
712    /// matches when it is the peer's display path or, for a rename, its old path. No
713    /// `--diff-filter` applies: ids must not depend on which statuses are shown.
714    ///
715    /// # Parameters
716    ///
717    /// - `side` - the side the primary changes came from.
718    /// - `pathspecs` - the pathspecs the primary changes were limited to.
719    /// - `renames` - rename detection, as for the primary changes.
720    /// - `primary_paths` - display paths of the primary changes.
721    ///
722    /// # Errors
723    ///
724    /// Returns [`RepositoryError::RequiresWorkTree`] for staged primaries in a bare repository, plus the
725    /// errors of [`Self::entries`] and of loading the changes.
726    pub fn peer_changes<'a>(
727        &mut self,
728        side: DiffSide,
729        pathspec: &crate::pathspec::Pathspec,
730        renames: RenameDetection,
731        primary_paths: impl IntoIterator<Item = &'a str>,
732    ) -> Result<Vec<FileChange>> {
733        let peer_target = match side {
734            DiffSide::Staged => DiffTarget::WorktreeVsIndex,
735            DiffSide::Unstaged => DiffTarget::IndexVsHead,
736            DiffSide::Other => return Ok(Vec::new()),
737        };
738        let primary: HashSet<&str> = primary_paths.into_iter().collect();
739        if primary.is_empty() {
740            return Ok(Vec::new());
741        }
742        let options = DiffOptions::default().with_renames(renames);
743        let entries: Vec<DiffEntry> = self
744            .entries(&peer_target, pathspec, &options)?
745            .entries
746            .into_iter()
747            .filter(|entry| {
748                let display = entry
749                    .new_path
750                    .as_deref()
751                    .or(entry.old_path.as_deref())
752                    .unwrap_or("");
753                peer_scope_includes_path(display, entry.old_path.as_deref(), &primary)
754            })
755            .collect();
756        match side {
757            DiffSide::Staged => self.load_worktree_changes(entries),
758            DiffSide::Unstaged | DiffSide::Other => load_object_changes(self.repo, &entries),
759        }
760    }
761
762    /// Load entries from [`Self::unstaged_entries`] or [`Self::worktree_entries`]: old sides
763    /// from the object database, new sides from the working tree (with gitlinks showing the
764    /// submodule's checked-out commit and `-dirty` state).
765    ///
766    /// # Errors
767    ///
768    /// Returns [`RepositoryError::RequiresWorkTree`] in a bare repository, plus I/O, filter, and object
769    /// read errors.
770    pub fn load_worktree_changes(&mut self, entries: Vec<DiffEntry>) -> Result<Vec<FileChange>> {
771        let work_tree = self.work_tree()?;
772        let rules = self.rules()?;
773        let side = WorktreeSide {
774            work_tree,
775            index: &self.index,
776            rules: &rules,
777        };
778        load_changes(self.repo.odb(), entries, Some(&side))
779    }
780
781    fn work_tree(&self) -> Result<&'repo Path> {
782        self.repo
783            .work_tree()
784            .ok_or(RepositoryError::RequiresWorkTree.into())
785    }
786
787    fn rules(&mut self) -> Result<Arc<Mutex<WorktreeRules>>> {
788        if let Some(rules) = &self.rules {
789            return Ok(Arc::clone(rules));
790        }
791        let rules = Arc::new(Mutex::new(WorktreeRules::from_repository(
792            self.repo,
793            &self.index,
794        )?));
795        self.rules = Some(Arc::clone(&rules));
796        Ok(rules)
797    }
798}
799
800#[cfg(test)]
801mod tests {
802    use super::*;
803    use crate::error::Error;
804    use crate::repo::{InitOptions, RepositoryError};
805
806    fn entry(status: DiffStatus, old: Option<&str>, new: Option<&str>) -> DiffEntry {
807        DiffEntry {
808            status,
809            old_path: old.map(str::to_owned),
810            new_path: new.map(str::to_owned),
811            old_mode: FileMode::REGULAR,
812            new_mode: FileMode::REGULAR,
813            old_oid: ObjectId::zero(),
814            new_oid: ObjectId::zero(),
815            score: Some(87),
816        }
817    }
818
819    #[test]
820    fn from_entry_keeps_old_path_only_for_real_renames() {
821        let bytes = || SideBytes::from_bytes(Vec::new());
822        let renamed = FileChange::from_entry(
823            entry(DiffStatus::Renamed, Some("a"), Some("b")),
824            bytes(),
825            bytes(),
826            false,
827        );
828        assert_eq!(renamed.path, "b");
829        assert_eq!(renamed.old_path.as_deref(), Some("a"));
830        assert_eq!(renamed.similarity, Some(87));
831
832        let deleted = FileChange::from_entry(
833            entry(DiffStatus::Deleted, Some("a"), None),
834            bytes(),
835            bytes(),
836            false,
837        );
838        assert_eq!(deleted.path, "a");
839        assert_eq!(deleted.old_path, None);
840        assert_eq!(deleted.similarity, None);
841    }
842
843    #[test]
844    fn binary_change_has_no_hunks_or_line_stat() {
845        let mut change = FileChange::from_entry(
846            entry(DiffStatus::Modified, Some("a"), Some("a")),
847            SideBytes::from_bytes(b"one\n".to_vec()),
848            SideBytes::from_bytes(b"two\n".to_vec()),
849            true,
850        );
851        assert!(change.structured(DiffOptions::default()).hunks.is_empty());
852        assert_eq!(change.line_stat(&DiffOptions::default()), None);
853
854        change.binary = false;
855        assert_eq!(change.structured(DiffOptions::default()).hunks.len(), 1);
856        assert_eq!(
857            change.line_stat(&DiffOptions::default()),
858            Some(LineStat {
859                insertions: 1,
860                deletions: 1,
861            })
862        );
863    }
864
865    #[test]
866    fn worktree_gitlink_line_reads_submodule_head_when_unhashed() {
867        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("tempdir: {e}"));
868        let mut gitlink = entry(DiffStatus::Added, None, Some("missing-sub"));
869        gitlink.old_mode = FileMode::ABSENT;
870        gitlink.new_mode = FileMode::GITLINK;
871        assert_eq!(worktree_gitlink_line(&gitlink, dir.path()), "");
872
873        let oid = ObjectId::from_hex("1111111111111111111111111111111111111111")
874            .unwrap_or_else(|e| panic!("oid: {e}"));
875        gitlink.new_oid = oid;
876        assert_eq!(
877            worktree_gitlink_line(&gitlink, dir.path()),
878            format!("Subproject commit {}\n", oid.to_hex())
879        );
880    }
881
882    /// Repository whose index tracks `files`, staged from the working tree.
883    fn staged_repo(files: &[(&str, &[u8])]) -> (tempfile::TempDir, Repository) {
884        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("tempdir: {e}"));
885        let (repo, _) = Repository::init(dir.path(), &InitOptions::default())
886            .unwrap_or_else(|e| panic!("init: {e}"));
887        for (path, bytes) in files {
888            std::fs::write(dir.path().join(path), bytes).unwrap_or_else(|e| panic!("write: {e}"));
889        }
890        crate::porcelain::add::stage(
891            &repo,
892            &crate::porcelain::add::StageOptions::default(),
893            &mut crate::progress::NullProgress,
894            &crate::progress::CancelToken::never(),
895        )
896        .unwrap_or_else(|e| panic!("stage: {e}"));
897        (dir, repo)
898    }
899
900    fn unstaged(repo: &Repository) -> Vec<DiffEntry> {
901        let index = repo.load_index().unwrap_or_else(|e| panic!("index: {e}"));
902        UncommittedDiff::new(repo, index)
903            .unstaged_entries(RenameDetection::Off)
904            .unwrap_or_else(|e| panic!("unstaged: {e}"))
905    }
906
907    #[test]
908    fn unstaged_size_change_is_reported_without_hashing() {
909        let (dir, repo) = staged_repo(&[("grown.txt", b"one\n"), ("same.txt", b"aaaa\n")]);
910        std::fs::write(dir.path().join("grown.txt"), b"one\ntwo\n")
911            .unwrap_or_else(|e| panic!("{e}"));
912        std::fs::write(dir.path().join("same.txt"), b"bbbb\n").unwrap_or_else(|e| panic!("{e}"));
913
914        let metrics = repo.odb().hot_path_metrics();
915        metrics.set_blob_counting(true);
916        metrics.reset_blob_content_reads();
917        let entries = unstaged(&repo);
918        // Only the same-size file is read (to hash it); the size change alone proves the other.
919        assert_eq!(metrics.blob_content_reads(), 1);
920        assert_eq!(entries.len(), 2);
921        let grown = &entries[0];
922        assert_eq!(grown.path(), "grown.txt");
923        assert_eq!(grown.status, DiffStatus::Modified);
924        assert_eq!(grown.new_oid, ObjectId::zero());
925        // A same-size edit is only reported once hashing proves the content changed.
926        let same = &entries[1];
927        assert_eq!(same.path(), "same.txt");
928        assert_eq!(same.status, DiffStatus::Modified);
929
930        let index = repo.load_index().unwrap_or_else(|e| panic!("index: {e}"));
931        let changes = UncommittedDiff::new(&repo, index)
932            .load_worktree_changes(entries)
933            .unwrap_or_else(|e| panic!("load: {e}"));
934        assert!(changes[0].content_changed);
935        assert_eq!(
936            changes[0].line_stat(&DiffOptions::default()),
937            Some(LineStat {
938                insertions: 1,
939                deletions: 0,
940            })
941        );
942    }
943
944    #[test]
945    fn binary_worktree_side_skips_reading_the_old_blob() {
946        let (dir, repo) = staged_repo(&[("data.bin", b"old text\n"), ("notes.txt", b"a\n")]);
947        std::fs::write(dir.path().join("data.bin"), b"new\0binary")
948            .unwrap_or_else(|e| panic!("{e}"));
949        std::fs::write(dir.path().join("notes.txt"), b"a\nb\n").unwrap_or_else(|e| panic!("{e}"));
950
951        let entries = unstaged(&repo);
952        let index = repo.load_index().unwrap_or_else(|e| panic!("index: {e}"));
953        let mut diff = UncommittedDiff::new(&repo, index);
954        let metrics = repo.odb().hot_path_metrics();
955        metrics.set_blob_counting(true);
956        metrics.reset_blob_content_reads();
957        let binary = diff
958            .load_worktree_changes(vec![entries[0].clone()])
959            .unwrap_or_else(|e| panic!("load: {e}"));
960        assert_eq!(binary[0].path, "data.bin");
961        assert!(binary[0].binary);
962        assert!(binary[0].content_changed);
963        // Only the working-tree file was read.
964        assert_eq!(metrics.blob_content_reads(), 1);
965
966        metrics.reset_blob_content_reads();
967        let text = diff
968            .load_worktree_changes(vec![entries[1].clone()])
969            .unwrap_or_else(|e| panic!("load: {e}"));
970        assert!(!text[0].binary);
971        assert_eq!(text[0].old_bytes.text(), "a\n");
972        assert_eq!(metrics.blob_content_reads(), 2);
973    }
974
975    #[test]
976    fn bare_repository_worktree_methods_require_a_work_tree() {
977        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("tempdir: {e}"));
978        let init = InitOptions {
979            bare: true,
980            ..InitOptions::default()
981        };
982        let (repo, _) = Repository::init(dir.path(), &init).unwrap_or_else(|e| panic!("init: {e}"));
983        let mut diff = UncommittedDiff::new(&repo, Index::default());
984        assert!(diff
985            .staged_entries(RenameDetection::Off)
986            .is_ok_and(|e| e.is_empty()));
987        assert!(matches!(
988            diff.unstaged_entries(RenameDetection::Off),
989            Err(Error::Repository(RepositoryError::RequiresWorkTree))
990        ));
991        assert!(matches!(
992            diff.worktree_entries(None, RenameDetection::Off),
993            Err(Error::Repository(RepositoryError::RequiresWorkTree))
994        ));
995        assert!(matches!(
996            diff.load_worktree_changes(Vec::new()),
997            Err(Error::Repository(RepositoryError::RequiresWorkTree))
998        ));
999    }
1000}