Skip to main content

grit_lib/diff/
has_changes.rs

1//! Fast change detection for diffs without building hunks.
2
3use std::path::Path;
4use std::sync::Arc;
5
6use crate::config::ConfigSet;
7use crate::diff::DiffTarget;
8use crate::diff::{
9    apply_rename_detection_to_diff_entries, diff_index_to_tree_with_renames,
10    diff_index_to_worktree_with_options, diff_tree_to_worktree_with_git_dir_and_rules,
11    diff_trees_with_renames_and_policy, index_mtime_for_diff, merge_file, tree_oid_of_commit,
12    DiffEntry, DiffIndexToWorktreeOptions, DiffOptions, DiffStatus,
13};
14use crate::error::{Error, Result};
15use crate::index::Index;
16use crate::objects::odb::Odb;
17use crate::objects::{parse_commit, ObjectId};
18use crate::pathspec::PathspecMatcher;
19use crate::repo::Repository;
20use crate::repo::RepositoryError;
21use crate::state::resolve_head_for_repository;
22use crate::worktree::worktree_rules::WorktreeRules;
23
24fn opts_need_content_compare(opts: &DiffOptions) -> bool {
25    opts.whitespace.is_active()
26}
27
28fn trust_filemode(config: &ConfigSet) -> bool {
29    config.file_mode()
30}
31
32fn rename_threshold(opts: &DiffOptions) -> u32 {
33    opts.renames.threshold_percent().unwrap_or(101)
34}
35
36/// Whether two text sides differ under whitespace options in `opts`.
37#[must_use]
38pub fn text_sides_differ(old: &str, new: &str, opts: &DiffOptions) -> bool {
39    if old == new {
40        return false;
41    }
42    let ws = opts.whitespace;
43    let (a, b) = preprocess_for_whitespace(old, new, ws);
44    if ws.ignore_blank_lines {
45        let a: Vec<_> = a.lines().filter(|l| !l.trim().is_empty()).collect();
46        let b: Vec<_> = b.lines().filter(|l| !l.trim().is_empty()).collect();
47        return a != b;
48    }
49    a != b
50}
51
52fn preprocess_for_whitespace(
53    old: &str,
54    new: &str,
55    ws: crate::diff::WhitespaceMode,
56) -> (String, String) {
57    if ws.ignore_all_space {
58        return (strip_all_whitespace(old), strip_all_whitespace(new));
59    }
60    if ws.ignore_space_change {
61        return (
62            crate::diff::normalize_ignore_space_change(old),
63            crate::diff::normalize_ignore_space_change(new),
64        );
65    }
66    if ws.ignore_space_at_eol {
67        return (trim_trailing_ws_lines(old), trim_trailing_ws_lines(new));
68    }
69    (old.to_owned(), new.to_owned())
70}
71
72fn strip_all_whitespace(s: &str) -> String {
73    s.lines()
74        .map(|line| {
75            line.chars()
76                .filter(|c| !c.is_whitespace())
77                .collect::<String>()
78        })
79        .collect::<Vec<_>>()
80        .join("\n")
81}
82
83fn trim_trailing_ws_lines(s: &str) -> String {
84    s.lines()
85        .map(|line| line.trim_end_matches(|c: char| c.is_whitespace()))
86        .collect::<Vec<_>>()
87        .join("\n")
88}
89
90fn worktree_file_index_blob_differ(
91    odb: &Odb,
92    work_tree: &Path,
93    rel_path: &str,
94    index_oid: &ObjectId,
95    opts: &DiffOptions,
96) -> Result<bool> {
97    let file_path = work_tree.join(rel_path);
98    let wt_bytes = std::fs::read(&file_path).map_err(Error::Io)?;
99    let index_raw = odb.read(index_oid)?.data;
100    if merge_file::is_binary(&wt_bytes) || merge_file::is_binary(&index_raw) {
101        return Ok(wt_bytes != index_raw);
102    }
103    let wt_s = String::from_utf8_lossy(&wt_bytes);
104    let idx_s = String::from_utf8_lossy(&index_raw);
105    Ok(text_sides_differ(&idx_s, &wt_s, opts))
106}
107
108fn worktree_index_entry_has_changes(
109    entry: &DiffEntry,
110    trust_fm: bool,
111    odb: &Odb,
112    work_tree: &Path,
113    opts: &DiffOptions,
114) -> Result<bool> {
115    match entry.status {
116        DiffStatus::Added
117        | DiffStatus::Deleted
118        | DiffStatus::TypeChanged
119        | DiffStatus::Unmerged => {
120            return Ok(true);
121        }
122        DiffStatus::Renamed | DiffStatus::Copied => return Ok(true),
123        DiffStatus::Modified => {}
124    }
125    if entry.old_mode != entry.new_mode && trust_fm {
126        return Ok(true);
127    }
128    let rel_path = entry.path();
129    let content_aware = opts_need_content_compare(opts);
130    if entry.new_oid.is_zero() && !entry.old_oid.is_zero() {
131        if content_aware {
132            return worktree_file_index_blob_differ(odb, work_tree, rel_path, &entry.old_oid, opts);
133        }
134        return Ok(true);
135    }
136    if entry.old_oid != entry.new_oid {
137        return blob_bytes_differ(odb, &entry.old_oid, &entry.new_oid, opts);
138    }
139    if content_aware {
140        return worktree_file_index_blob_differ(odb, work_tree, rel_path, &entry.old_oid, opts);
141    }
142    Ok(true)
143}
144
145fn blob_bytes_differ(
146    odb: &Odb,
147    old_oid: &ObjectId,
148    new_oid: &ObjectId,
149    opts: &DiffOptions,
150) -> Result<bool> {
151    if old_oid == new_oid {
152        return Ok(false);
153    }
154    let old_raw = odb.read(old_oid)?.data;
155    let new_raw = odb.read(new_oid)?.data;
156    if merge_file::is_binary(&old_raw) || merge_file::is_binary(&new_raw) {
157        return Ok(old_raw != new_raw);
158    }
159    let old_s = String::from_utf8_lossy(&old_raw);
160    let new_s = String::from_utf8_lossy(&new_raw);
161    Ok(text_sides_differ(&old_s, &new_s, opts))
162}
163
164/// Whether a tree/index diff entry counts as a real change for `--exit-code` semantics.
165pub(crate) fn tree_entry_has_changes(
166    odb: &Odb,
167    entry: &DiffEntry,
168    trust_fm: bool,
169    opts: &DiffOptions,
170) -> Result<bool> {
171    match entry.status {
172        DiffStatus::Added
173        | DiffStatus::Deleted
174        | DiffStatus::TypeChanged
175        | DiffStatus::Unmerged => {
176            return Ok(true);
177        }
178        DiffStatus::Renamed | DiffStatus::Copied => return Ok(true),
179        DiffStatus::Modified => {}
180    }
181    if entry.old_mode != entry.new_mode && trust_fm {
182        return Ok(true);
183    }
184    // Index↔worktree diffs use the null OID on the worktree side when content differs.
185    if entry.new_oid.is_zero() && !entry.old_oid.is_zero() {
186        return Ok(true);
187    }
188    if entry.old_oid.is_zero() && !entry.new_oid.is_zero() {
189        return Ok(true);
190    }
191    if entry.old_oid != entry.new_oid {
192        return blob_bytes_differ(odb, &entry.old_oid, &entry.new_oid, opts);
193    }
194    Ok(false)
195}
196
197fn worktree_has_changes(
198    repo: &Repository,
199    index: &mut Index,
200    base_tree: Option<&ObjectId>,
201    matcher: &PathspecMatcher<'_>,
202    opts: &DiffOptions,
203) -> Result<bool> {
204    let work_tree = repo.work_tree().ok_or(RepositoryError::RequiresWorkTree)?;
205    let config = repo.config().snapshot()?;
206    let index_mtime = index_mtime_for_diff(index, None);
207    let rules_arc = Arc::new(std::sync::Mutex::new(WorktreeRules::from_repository(
208        repo, index,
209    )?));
210
211    let cache_valid =
212        crate::index::write_tree::cache_tree_extension_valid(index.cache_tree.as_ref());
213    let index_backed = match base_tree {
214        // Unstaged diffs are always index vs worktree.
215        None => true,
216        Some(tree) => {
217            index
218                .cache_tree_root
219                .as_ref()
220                .is_some_and(|root| root == tree)
221                && cache_valid
222        }
223    };
224
225    if index_backed {
226        crate::test_probe_hooks::hooks::reset_worktree_has_changes_scan();
227        let content_compare = opts_need_content_compare(opts);
228        let (entries, _) = diff_index_to_worktree_with_options(
229            repo.odb(),
230            index,
231            work_tree,
232            DiffIndexToWorktreeOptions {
233                repository_git_dir: Some(repo.git_dir().to_path_buf()),
234                index_mtime,
235                config: Some(Arc::clone(&config)),
236                thread_policy: Some(repo.thread_policy()),
237                refresh_index_stat_in_pass: false,
238                for_status: !content_compare,
239                worktree_rules: Some(Arc::clone(&rules_arc)),
240                ..DiffIndexToWorktreeOptions::default()
241            },
242        )?;
243        for entry in &entries {
244            crate::test_probe_hooks::hooks::worktree_has_changes_entry_scanned();
245            if !matcher.matches_change(entry.path(), entry.old_path.as_deref()) {
246                continue;
247            }
248            if worktree_index_entry_has_changes(
249                entry,
250                trust_filemode(config.as_ref()),
251                repo.odb(),
252                work_tree,
253                opts,
254            )? {
255                return Ok(true);
256            }
257        }
258        return Ok(false);
259    }
260
261    let worktree_rules = WorktreeRules::from_repository(repo, index)?;
262    let raw = diff_tree_to_worktree_with_git_dir_and_rules(
263        repo.odb(),
264        base_tree,
265        work_tree,
266        repo.git_dir(),
267        index,
268        Some(config.as_ref()),
269        Some(&worktree_rules),
270    )?;
271    let entries = apply_rename_detection_to_diff_entries(
272        repo.odb(),
273        raw,
274        Some(work_tree),
275        rename_threshold(opts),
276        config.as_ref(),
277        &repo.thread_policy(),
278    )?;
279    for entry in entries {
280        if !matcher.matches_change(entry.path(), entry.old_path.as_deref()) {
281            continue;
282        }
283        if tree_entry_has_changes(repo.odb(), &entry, trust_filemode(config.as_ref()), opts)? {
284            return Ok(true);
285        }
286    }
287    Ok(false)
288}
289
290fn staged_has_changes(
291    repo: &Repository,
292    matcher: &PathspecMatcher<'_>,
293    opts: &DiffOptions,
294) -> Result<bool> {
295    let head_tree = resolve_head_for_repository(repo)?.tree(repo.odb())?;
296    let index = repo.load_index()?;
297    let config = repo.config().snapshot()?;
298    let mut entries = diff_index_to_tree_with_renames(
299        repo.odb(),
300        &index,
301        head_tree.as_ref(),
302        false,
303        rename_threshold(opts),
304        config.as_ref(),
305        &repo.thread_policy(),
306    )?;
307    for entry in entries.drain(..) {
308        if !matcher.matches_change(entry.path(), entry.old_path.as_deref()) {
309            continue;
310        }
311        if tree_entry_has_changes(repo.odb(), &entry, trust_filemode(config.as_ref()), opts)? {
312            return Ok(true);
313        }
314    }
315    Ok(false)
316}
317
318fn unstaged_has_changes(
319    repo: &Repository,
320    matcher: &PathspecMatcher<'_>,
321    opts: &DiffOptions,
322) -> Result<bool> {
323    let mut index = repo.load_index()?;
324    worktree_has_changes(repo, &mut index, None, matcher, opts)
325}
326
327fn commit_trees_has_changes(
328    repo: &Repository,
329    base: &ObjectId,
330    tip: &ObjectId,
331    matcher: &PathspecMatcher<'_>,
332    opts: &DiffOptions,
333) -> Result<bool> {
334    let config = repo.config().snapshot()?;
335    let base_tree = tree_oid_of_commit(repo.odb(), base)?;
336    let tip_tree = tree_oid_of_commit(repo.odb(), tip)?;
337    let mut entries = diff_trees_with_renames_and_policy(
338        repo.odb(),
339        Some(&base_tree),
340        Some(&tip_tree),
341        "",
342        rename_threshold(opts),
343        config.as_ref(),
344        &repo.thread_policy(),
345    )?;
346    for entry in entries.drain(..) {
347        if !matcher.matches_change(entry.path(), entry.old_path.as_deref()) {
348            continue;
349        }
350        if tree_entry_has_changes(repo.odb(), &entry, trust_filemode(config.as_ref()), opts)? {
351            return Ok(true);
352        }
353    }
354    Ok(false)
355}
356
357impl<'repo> super::handle::Diff<'repo> {
358    /// Whether the selected diff has any real changes, stopping at the first one.
359    ///
360    /// Worktree targets honor the index stat cache and only hash blob content when needed.
361    /// When whitespace ignore flags are set on `opts`, content is compared under those rules;
362    /// a change that differs only in ignored whitespace returns `false`.
363    ///
364    /// # Errors
365    ///
366    /// Propagates repository, ODB, and diff errors.
367    pub fn has_changes(
368        &self,
369        target: &DiffTarget,
370        pathspec: &crate::pathspec::Pathspec,
371        opts: &DiffOptions,
372    ) -> Result<bool> {
373        crate::test_probe_hooks::hooks::has_changes_call();
374        let repo = self.repository();
375        let matcher = repo.pathspec_matcher_with_globals(pathspec.specs(), pathspec.globals())?;
376        match target {
377            DiffTarget::WorktreeVsHead => {
378                let mut index = repo.load_index()?;
379                let head_tree = resolve_head_for_repository(repo)?.tree(repo.odb())?;
380                worktree_has_changes(repo, &mut index, head_tree.as_ref(), &matcher, opts)
381            }
382            DiffTarget::IndexVsHead => staged_has_changes(repo, &matcher, opts),
383            DiffTarget::WorktreeVsIndex => unstaged_has_changes(repo, &matcher, opts),
384            DiffTarget::WorktreeVsTree(tree) => {
385                let mut index = repo.load_index()?;
386                worktree_has_changes(repo, &mut index, Some(tree), &matcher, opts)
387            }
388            DiffTarget::Commit(commit) => {
389                let obj = repo.odb().read(commit)?;
390                let parsed = parse_commit(&obj.data)?;
391                let new_tree = parsed.tree;
392                let old_tree = parsed
393                    .parents
394                    .first()
395                    .map(|parent| tree_oid_of_commit(repo.odb(), parent))
396                    .transpose()?;
397                let config = repo.config().snapshot()?;
398                let mut entries = diff_trees_with_renames_and_policy(
399                    repo.odb(),
400                    old_tree.as_ref(),
401                    Some(&new_tree),
402                    "",
403                    rename_threshold(opts),
404                    config.as_ref(),
405                    &repo.thread_policy(),
406                )?;
407                for entry in entries.drain(..) {
408                    if !matcher.matches_change(entry.path(), entry.old_path.as_deref()) {
409                        continue;
410                    }
411                    if tree_entry_has_changes(
412                        repo.odb(),
413                        &entry,
414                        trust_filemode(config.as_ref()),
415                        opts,
416                    )? {
417                        return Ok(true);
418                    }
419                }
420                Ok(false)
421            }
422            DiffTarget::Trees { old, new } => match old {
423                Some(base) => commit_trees_has_changes(repo, base, new, &matcher, opts),
424                None => {
425                    let config = repo.config().snapshot()?;
426                    let tip_tree = super::core::tree_oid_for_diff_side(repo.odb(), new)?;
427                    let mut entries = diff_trees_with_renames_and_policy(
428                        repo.odb(),
429                        None,
430                        Some(&tip_tree),
431                        "",
432                        rename_threshold(opts),
433                        config.as_ref(),
434                        &repo.thread_policy(),
435                    )?;
436                    for entry in entries.drain(..) {
437                        if !matcher.matches_change(entry.path(), entry.old_path.as_deref()) {
438                            continue;
439                        }
440                        if tree_entry_has_changes(
441                            repo.odb(),
442                            &entry,
443                            trust_filemode(config.as_ref()),
444                            opts,
445                        )? {
446                            return Ok(true);
447                        }
448                    }
449                    Ok(false)
450                }
451            },
452        }
453    }
454}