Skip to main content

grit_lib/diff/
no_index.rs

1//! Compare arbitrary filesystem paths without a repository (`git diff --no-index`).
2
3use std::collections::{BTreeSet, HashSet};
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use thiserror::Error;
8
9use crate::config::ConfigSet;
10use crate::hash::hash_object;
11use crate::objects::FileMode;
12use crate::objects::{HashAlgo, ObjectId, ObjectKind};
13use crate::odb::Odb;
14use crate::parallel::ThreadPolicy;
15
16use super::core::{
17    apply_rename_detection_to_diff_entries, mode_from_metadata, read_worktree_bytes_for_mode,
18    zero_oid, DiffEntry, DiffStatus,
19};
20use super::detail::line_change_counts;
21use super::options::DiffOptions;
22use super::patch_log::{write_patch, PatchTextOptions};
23use super::structured::{structured_file_diff, SideBytes};
24use super::targets::FileDiff;
25use crate::repo::{InitOptions, Repository};
26
27const S_IFMT: u32 = 0o170000;
28const S_IFREG: u32 = 0o100000;
29
30/// Failure modes specific to [`diff_paths`].
31#[derive(Debug, Error, Clone, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum NoIndexError {
34    /// A path could not be read (missing or permission denied).
35    #[error("Could not access '{path}'")]
36    PathNotAccessible {
37        /// Filesystem path that could not be accessed.
38        path: String,
39    },
40    /// SHA-1 collision detection rejected blob content while hashing a path.
41    #[error("sha-1 hash collision while hashing no-index diff input")]
42    HashCollision,
43}
44
45impl From<NoIndexError> for crate::error::Error {
46    fn from(value: NoIndexError) -> Self {
47        Self::Message(value.to_string())
48    }
49}
50
51/// Diff two filesystem paths (files, directories, or one of each).
52///
53/// Does not require a [`Repository`](crate::repo::Repository). Directory pairs are walked
54/// recursively with sorted names; a file paired with a directory compares against
55/// `directory/basename(file)` like Git. Symlink targets are diffed as text; executable
56/// bit differences appear as mode changes.
57///
58/// # Errors
59///
60/// Returns [`NoIndexError::PathNotAccessible`] when either top-level path cannot be accessed.
61pub fn diff_paths(a: &Path, b: &Path, opts: &DiffOptions) -> Result<Vec<FileDiff>, NoIndexError> {
62    let stat_only = opts.no_index_stat_only;
63    let temp = tempfile::tempdir().map_err(|e| NoIndexError::PathNotAccessible {
64        path: e.to_string(),
65    })?;
66    let odb = Odb::new(temp.path());
67    let entries = no_index_prepared_entries(a, b, opts, &odb)?;
68    if entries.is_empty() {
69        return Ok(Vec::new());
70    }
71    let diff_options = opts
72        .clone()
73        .cap_word_level_inline_for_changed_files(entries.len());
74    Ok(entries
75        .into_iter()
76        .filter_map(|entry| file_diff_from_entry(&odb, &entry, diff_options.clone(), stat_only))
77        .collect())
78}
79
80/// Write `git diff --no-index --binary`-style patch bytes for two filesystem paths.
81///
82/// Returns `Ok(true)` when the paths differ.
83///
84/// # Errors
85///
86/// Propagates [`NoIndexError`] and repository/patch I/O failures.
87pub fn write_paths_patch<W: std::io::Write>(
88    a: &Path,
89    b: &Path,
90    opts: &DiffOptions,
91    out: &mut W,
92) -> Result<bool, NoIndexError> {
93    let temp = tempfile::tempdir().map_err(|e| NoIndexError::PathNotAccessible {
94        path: e.to_string(),
95    })?;
96    let repo = Repository::init(temp.path(), &InitOptions::new().with_bare(true)).map_err(|e| {
97        NoIndexError::PathNotAccessible {
98            path: e.to_string(),
99        }
100    })?;
101    let entries = no_index_prepared_entries(a, b, opts, repo.odb())?;
102    if entries.is_empty() {
103        return Ok(false);
104    }
105    let patch_opts = PatchTextOptions::from_repo(&repo, opts.clone()).map_err(|e| {
106        NoIndexError::PathNotAccessible {
107            path: e.to_string(),
108        }
109    })?;
110    write_patch(&repo, &entries, &patch_opts, out).map_err(|e| {
111        NoIndexError::PathNotAccessible {
112            path: e.to_string(),
113        }
114    })?;
115    Ok(true)
116}
117
118fn no_index_prepared_entries(
119    a: &Path,
120    b: &Path,
121    opts: &DiffOptions,
122    odb: &Odb,
123) -> Result<Vec<DiffEntry>, NoIndexError> {
124    let (left, right) = fixup_paths(a, b)?;
125    let mut entries = Vec::new();
126    queue_diff(left.as_deref(), right.as_deref(), false, &mut entries)?;
127    if entries.is_empty() {
128        return Ok(entries);
129    }
130
131    let config = ConfigSet::default();
132    let thread_policy = ThreadPolicy::default();
133    let rename_threshold = opts.renames.threshold_percent().unwrap_or(101);
134    store_changed_blobs(odb, &mut entries)?;
135    if rename_threshold < 100 {
136        apply_rename_detection_to_diff_entries(
137            odb,
138            entries,
139            None,
140            rename_threshold,
141            &config,
142            &thread_policy,
143        )
144        .map_err(|e| NoIndexError::PathNotAccessible {
145            path: e.to_string(),
146        })
147    } else {
148        Ok(entries)
149    }
150}
151
152fn file_diff_from_entry(
153    odb: &Odb,
154    entry: &DiffEntry,
155    opts: DiffOptions,
156    stat_only: bool,
157) -> Option<FileDiff> {
158    let path_unchanged = entry.old_path == entry.new_path;
159    if entry.old_oid == entry.new_oid
160        && entry.old_mode == entry.new_mode
161        && path_unchanged
162        && !matches!(entry.status, DiffStatus::Renamed | DiffStatus::Copied)
163    {
164        return None;
165    }
166    let (old_bytes, old_bin) = side_bytes_for_entry(odb, entry, Side::Old)?;
167    let (new_bytes, new_bin) = side_bytes_for_entry(odb, entry, Side::New)?;
168    let binary = old_bin || new_bin;
169    let path = entry
170        .new_path
171        .clone()
172        .or_else(|| entry.old_path.clone())
173        .unwrap_or_default();
174    let old_path = entry
175        .old_path
176        .clone()
177        .filter(|op| entry.new_path.as_ref() != Some(op));
178    let (old_encoding_lossy, new_encoding_lossy, hunks, line_stat) = if binary {
179        (
180            old_bytes.encoding_lossy,
181            new_bytes.encoding_lossy,
182            Vec::new(),
183            None,
184        )
185    } else if stat_only {
186        let old_text = String::from_utf8_lossy(&old_bytes.data);
187        let new_text = String::from_utf8_lossy(&new_bytes.data);
188        let stat = line_change_counts(old_text.as_ref(), new_text.as_ref(), &opts);
189        (
190            old_bytes.encoding_lossy,
191            new_bytes.encoding_lossy,
192            Vec::new(),
193            Some(stat),
194        )
195    } else {
196        let structured =
197            structured_file_diff(entry.old_mode, entry.new_mode, &old_bytes, &new_bytes, opts);
198        (
199            structured.old_encoding_lossy,
200            structured.new_encoding_lossy,
201            structured.hunks,
202            None,
203        )
204    };
205    Some(FileDiff {
206        path,
207        old_path,
208        status: entry.status,
209        old_mode: entry.old_mode.octal_if_present(),
210        new_mode: entry.new_mode.octal_if_present(),
211        old_oid: entry.old_oid,
212        new_oid: entry.new_oid,
213        binary,
214        content_changed: entry.old_oid != entry.new_oid,
215        old_encoding_lossy,
216        new_encoding_lossy,
217        hunks,
218        line_stat,
219    })
220}
221
222enum Side {
223    Old,
224    New,
225}
226
227fn side_bytes_for_entry(odb: &Odb, entry: &DiffEntry, side: Side) -> Option<(SideBytes, bool)> {
228    let (mode, oid) = match side {
229        Side::Old => (entry.old_mode, entry.old_oid),
230        Side::New => (entry.new_mode, entry.new_oid),
231    };
232    if mode.is_absent() {
233        return Some((SideBytes::from_bytes(Vec::new()), false));
234    }
235    let data = odb.read(&oid).ok()?.data;
236    Some(bytes_for_diff(&data))
237}
238
239fn bytes_for_diff(data: &[u8]) -> (SideBytes, bool) {
240    let binary = crate::merge_file::is_binary(data);
241    (SideBytes::from_bytes(data.to_vec()), binary)
242}
243
244/// Write blob objects for changed sides only (rename detection reads from the ODB).
245fn store_changed_blobs(odb: &Odb, entries: &mut [DiffEntry]) -> Result<(), NoIndexError> {
246    for entry in entries {
247        if entry.old_mode != FileMode::ABSENT && !entry.old_oid.is_zero() {
248            if let Some(path) = entry.old_path.as_deref() {
249                write_blob_if_missing(odb, path, entry.old_mode, &mut entry.old_oid)?;
250            }
251        }
252        if entry.new_mode != FileMode::ABSENT && !entry.new_oid.is_zero() {
253            if let Some(path) = entry.new_path.as_deref() {
254                write_blob_if_missing(odb, path, entry.new_mode, &mut entry.new_oid)?;
255            }
256        }
257    }
258    Ok(())
259}
260
261fn write_blob_if_missing(
262    odb: &Odb,
263    path: &str,
264    mode: FileMode,
265    oid: &mut ObjectId,
266) -> Result<(), NoIndexError> {
267    if !oid.is_zero() && odb.read(oid).is_ok() {
268        return Ok(());
269    }
270    *oid = hash_side_at_path(path, mode)?;
271    let data = read_worktree_bytes_for_mode(Path::new(path), mode.bits()).map_err(|_| {
272        NoIndexError::PathNotAccessible {
273            path: path.to_owned(),
274        }
275    })?;
276    let _ = odb.write(ObjectKind::Blob, &data);
277    Ok(())
278}
279
280fn hash_side_at_path(path: &str, mode: FileMode) -> Result<ObjectId, NoIndexError> {
281    let data = read_worktree_bytes_for_mode(Path::new(path), mode.bits()).map_err(|_| {
282        NoIndexError::PathNotAccessible {
283            path: path.to_owned(),
284        }
285    })?;
286    hash_blob(&data)
287}
288
289fn hash_blob(data: &[u8]) -> Result<ObjectId, NoIndexError> {
290    hash_object(HashAlgo::Sha1, ObjectKind::Blob, data).map_err(|e| match e {
291        crate::error::Error::HashCollision { .. } => NoIndexError::HashCollision,
292        other => panic!("unexpected error hashing no-index blob: {other}"),
293    })
294}
295
296fn read_side_bytes(path: &Path, mode: u32) -> Result<Vec<u8>, NoIndexError> {
297    read_worktree_bytes_for_mode(path, mode).map_err(|_| NoIndexError::PathNotAccessible {
298        path: path.display().to_string(),
299    })
300}
301
302fn worktree_content_equal(
303    left: &Path,
304    right: &Path,
305    mode_left: u32,
306    mode_right: u32,
307) -> Result<bool, NoIndexError> {
308    let (ls, rs) = (
309        fs::metadata(left).map(|m| m.len()).ok(),
310        fs::metadata(right).map(|m| m.len()).ok(),
311    );
312    if ls != rs {
313        return Ok(false);
314    }
315    let old_bytes = read_side_bytes(left, mode_left)?;
316    let new_bytes = read_side_bytes(right, mode_right)?;
317    Ok(old_bytes == new_bytes)
318}
319
320/// Blob OIDs for a path pair, reading each present side at most once.
321fn oids_for_pair(
322    left: Option<&Path>,
323    right: Option<&Path>,
324    mode_left: u32,
325    mode_right: u32,
326) -> Result<(ObjectId, ObjectId), NoIndexError> {
327    match (left, right) {
328        (Some(l), Some(r)) if mode_left != 0 && mode_right != 0 => {
329            let old_bytes = read_side_bytes(l, mode_left)?;
330            let new_bytes = read_side_bytes(r, mode_right)?;
331            let old_oid = hash_blob(&old_bytes)?;
332            let new_oid = if old_bytes == new_bytes {
333                old_oid
334            } else {
335                hash_blob(&new_bytes)?
336            };
337            Ok((old_oid, new_oid))
338        }
339        (Some(l), _) if mode_left != 0 => {
340            let old_bytes = read_side_bytes(l, mode_left)?;
341            Ok((hash_blob(&old_bytes)?, zero_oid()))
342        }
343        (_, Some(r)) if mode_right != 0 => {
344            let new_bytes = read_side_bytes(r, mode_right)?;
345            Ok((zero_oid(), hash_blob(&new_bytes)?))
346        }
347        _ => Ok((zero_oid(), zero_oid())),
348    }
349}
350
351fn fixup_paths(a: &Path, b: &Path) -> Result<(Option<PathBuf>, Option<PathBuf>), NoIndexError> {
352    let meta_a = fs::symlink_metadata(a).ok();
353    let meta_b = fs::symlink_metadata(b).ok();
354    if meta_a.is_none() && meta_b.is_none() {
355        return Err(NoIndexError::PathNotAccessible {
356            path: a.display().to_string(),
357        });
358    }
359    let is_dir_a = meta_a.as_ref().is_some_and(|m| m.is_dir());
360    let is_dir_b = meta_b.as_ref().is_some_and(|m| m.is_dir());
361    if is_dir_a && is_dir_b {
362        return Ok((Some(a.to_path_buf()), Some(b.to_path_buf())));
363    }
364    if is_dir_a {
365        let mut joined = a.to_path_buf();
366        append_basename(&mut joined, b);
367        return Ok((Some(joined), Some(b.to_path_buf())));
368    }
369    if is_dir_b {
370        let mut joined = b.to_path_buf();
371        append_basename(&mut joined, a);
372        return Ok((Some(a.to_path_buf()), Some(joined)));
373    }
374    Ok((Some(a.to_path_buf()), Some(b.to_path_buf())))
375}
376
377fn append_basename(dir: &mut PathBuf, file: &Path) {
378    let name = file.file_name().unwrap_or_default();
379    if name.is_empty() {
380        return;
381    }
382    strip_trailing_slashes_preserve_root(dir);
383    dir.push(name);
384}
385
386/// Remove trailing `/` without turning `/` into an empty relative path.
387fn strip_trailing_slashes_preserve_root(path: &mut PathBuf) {
388    let raw = path.as_os_str().to_string_lossy();
389    let trimmed = raw.trim_end_matches('/');
390    if trimmed.is_empty() {
391        *path = PathBuf::from("/");
392    } else {
393        *path = PathBuf::from(trimmed);
394    }
395}
396
397fn queue_diff(
398    left: Option<&Path>,
399    right: Option<&Path>,
400    recursing: bool,
401    out: &mut Vec<DiffEntry>,
402) -> Result<(), NoIndexError> {
403    let (mode_left, mode_right) = (path_mode(left, recursing)?, path_mode(right, recursing)?);
404    let dir_left = path_is_dir(left);
405    let dir_right = path_is_dir(right);
406
407    if mode_left != 0 && mode_right != 0 && dir_left != dir_right {
408        if dir_left {
409            emit_pair(
410                out,
411                None,
412                right,
413                0,
414                mode_right,
415                right.map(path_display_string),
416            )?;
417            return queue_diff(left, None, true, out);
418        }
419        emit_pair(out, left, None, mode_left, 0, left.map(path_display_string))?;
420        return queue_diff(None, right, true, out);
421    }
422
423    if dir_left || dir_right {
424        diff_directories(left, right, out)
425    } else {
426        emit_pair(
427            out,
428            left,
429            right,
430            mode_left,
431            mode_right,
432            left.or(right).map(path_display_string),
433        )?;
434        Ok(())
435    }
436}
437
438fn path_is_dir(path: Option<&Path>) -> bool {
439    path.and_then(|p| fs::symlink_metadata(p).ok())
440        .is_some_and(|m| m.is_dir())
441}
442
443fn diff_directories(
444    left: Option<&Path>,
445    right: Option<&Path>,
446    out: &mut Vec<DiffEntry>,
447) -> Result<(), NoIndexError> {
448    let left_names = read_dir_names(left)?;
449    let right_names = read_dir_names(right)?;
450    let left_set: HashSet<_> = left_names.iter().cloned().collect();
451    let right_set: HashSet<_> = right_names.iter().cloned().collect();
452    let names: BTreeSet<_> = left_names
453        .iter()
454        .chain(right_names.iter())
455        .cloned()
456        .collect();
457    for name in names {
458        let l = left
459            .filter(|_| left_set.contains(&name))
460            .map(|p| p.join(&name));
461        let r = right
462            .filter(|_| right_set.contains(&name))
463            .map(|p| p.join(&name));
464        queue_diff(l.as_deref(), r.as_deref(), true, out)?;
465    }
466    Ok(())
467}
468
469fn read_dir_names(path: Option<&Path>) -> Result<Vec<String>, NoIndexError> {
470    let Some(path) = path else {
471        return Ok(Vec::new());
472    };
473    let mut names = Vec::new();
474    let read_dir = fs::read_dir(path).map_err(|_| NoIndexError::PathNotAccessible {
475        path: path.display().to_string(),
476    })?;
477    for entry in read_dir {
478        let entry = entry.map_err(|_| NoIndexError::PathNotAccessible {
479            path: path.display().to_string(),
480        })?;
481        let name = entry.file_name().to_string_lossy().into_owned();
482        if name == "." || name == ".." {
483            continue;
484        }
485        names.push(name);
486    }
487    names.sort();
488    Ok(names)
489}
490
491fn emit_pair(
492    out: &mut Vec<DiffEntry>,
493    left: Option<&Path>,
494    right: Option<&Path>,
495    mode_left: u32,
496    mode_right: u32,
497    display: Option<String>,
498) -> Result<(), NoIndexError> {
499    let (status, old_path, new_path) = match (left, right) {
500        (Some(_l), Some(_r)) if mode_left == 0 || mode_right == 0 => {
501            if mode_left == 0 {
502                (DiffStatus::Added, None, display.clone())
503            } else {
504                (DiffStatus::Deleted, display.clone(), None)
505            }
506        }
507        (Some(l), None) => (DiffStatus::Deleted, Some(path_display_string(l)), None),
508        (None, Some(r)) => (DiffStatus::Added, None, Some(path_display_string(r))),
509        (Some(l), Some(r)) => {
510            let lp = path_display_string(l);
511            let rp = path_display_string(r);
512            let status = if file_kind(mode_left) != file_kind(mode_right) {
513                DiffStatus::TypeChanged
514            } else {
515                DiffStatus::Modified
516            };
517            (status, Some(lp), Some(rp))
518        }
519        (None, None) => return Ok(()),
520    };
521
522    let old_mode = FileMode::new(mode_left);
523    let new_mode = FileMode::new(mode_right);
524
525    if let (Some(l), Some(r)) = (left, right) {
526        if mode_left != 0
527            && mode_right != 0
528            && old_mode == new_mode
529            && worktree_content_equal(l, r, mode_left, mode_right)?
530        {
531            return Ok(());
532        }
533    }
534
535    let (old_oid, new_oid) = oids_for_pair(left, right, mode_left, mode_right)?;
536
537    if old_oid == new_oid && old_mode == new_mode {
538        return Ok(());
539    }
540
541    out.push(DiffEntry {
542        status,
543        old_path,
544        new_path,
545        old_mode,
546        new_mode,
547        old_oid,
548        new_oid,
549        score: None,
550    });
551    Ok(())
552}
553
554fn file_kind(mode: u32) -> u32 {
555    if mode & S_IFMT != 0 {
556        mode & S_IFMT
557    } else {
558        S_IFREG
559    }
560}
561
562fn path_mode(path: Option<&Path>, recursing: bool) -> Result<u32, NoIndexError> {
563    let Some(path) = path else {
564        return Ok(0);
565    };
566    if !recursing && path.as_os_str().is_empty() {
567        return Ok(0);
568    }
569    match fs::symlink_metadata(path) {
570        Ok(meta) => Ok(mode_from_metadata(&meta)),
571        Err(_) if recursing => Ok(0),
572        Err(_) => Err(NoIndexError::PathNotAccessible {
573            path: path.display().to_string(),
574        }),
575    }
576}
577
578fn path_display_string(path: &Path) -> String {
579    path.to_string_lossy().into_owned()
580}