Skip to main content

gix_diff/rewrites/
tracker.rs

1//! ### Deviation
2//!
3//! Note that the algorithm implemented here is in many ways different from what `git` does.
4//!
5//! - it's less sophisticated than `git`, but prefers a candidate whose file name matches the
6//!   destination's in identity matches, and uses that as a tie-breaker for similarity matches.
7//! - the set used for copy-detection is probably smaller by default.
8// TODO: Rewrite this based on what Git actually this, as long as there are test-cases for any 'complication'.
9//       In practice, even this simplified version seems to have worked pretty well.
10
11use std::ops::Range;
12
13use bstr::{BStr, ByteSlice};
14use gix_object::tree::{EntryKind, EntryMode};
15
16use crate::{
17    Rewrites,
18    blob::{DiffLineStats, ResourceKind, platform::prepare_diff::Operation},
19    rewrites::{CopySource, Outcome, Tracker, tracker::visit::SourceKind},
20    tree::visit::{Action, ChangeId, Relation},
21};
22
23/// The kind of a change.
24#[derive(Debug, Copy, Clone, Ord, PartialOrd, PartialEq, Eq)]
25pub enum ChangeKind {
26    /// The change represents the *deletion* of an item.
27    Deletion,
28    /// The change represents the *modification* of an item.
29    Modification,
30    /// The change represents the *addition* of an item.
31    Addition,
32}
33
34/// A trait providing all functionality to abstract over the concept of a change, as seen by the [`Tracker`].
35pub trait Change: Clone {
36    /// Return the hash of the object behind this change for identification.
37    ///
38    /// Note that this is the id of the object as stored in `git`, i.e. it must have gone through workspace
39    /// conversions. What matters is that the IDs are comparable.
40    fn id(&self) -> &gix_hash::oid;
41    /// Return the relation that this change may have with other changes.
42    ///
43    /// It allows to associate a directory with its children that are added or removed at the same moment.
44    /// Note that this is ignored for modifications.
45    ///
46    /// If rename-tracking should always be on leaf-level, this should be set to `None` consistently.
47    /// Note that trees will never be looked up by their `id` as their children are assumed to be passed in
48    /// with the respective relationship.
49    ///
50    /// Also note that the tracker only sees what's given to it, it will not lookup trees or match paths itself.
51    fn relation(&self) -> Option<Relation>;
52    /// Return the kind of this change.
53    fn kind(&self) -> ChangeKind;
54    /// Return more information about the kind of entry affected by this change.
55    fn entry_mode(&self) -> EntryMode;
56    /// Return the id of the change along with its mode.
57    fn id_and_entry_mode(&self) -> (&gix_hash::oid, EntryMode);
58}
59
60/// A set of tracked items allows to figure out their relations by figuring out their similarity.
61pub(crate) struct Item<T> {
62    /// The underlying raw change
63    change: T,
64    /// That slice into the backing for paths.
65    path: Range<usize>,
66    /// If true, this item was already emitted, i.e. seen by the caller.
67    emitted: bool,
68}
69
70impl<T: Change> Item<T> {
71    fn location<'a>(&self, backing: &'a [u8]) -> &'a BStr {
72        backing[self.path.clone()].as_ref()
73    }
74    fn entry_mode_compatible(&self, other: EntryMode) -> bool {
75        use EntryKind::*;
76        matches!(
77            (other.kind(), self.change.entry_mode().kind()),
78            (Blob | BlobExecutable, Blob | BlobExecutable) | (Link, Link) | (Tree, Tree)
79        )
80    }
81
82    fn is_source_for_destination_of(&self, kind: visit::SourceKind, dest_item_mode: EntryMode) -> bool {
83        self.entry_mode_compatible(dest_item_mode)
84            && match kind {
85                visit::SourceKind::Rename => !self.emitted && matches!(self.change.kind(), ChangeKind::Deletion),
86                visit::SourceKind::Copy => {
87                    matches!(self.change.kind(), ChangeKind::Modification)
88                }
89            }
90    }
91}
92
93/// A module with types used in the user-callback in [Tracker::emit()](crate::rewrites::Tracker::emit()).
94pub mod visit {
95    use bstr::BStr;
96    use gix_object::tree::EntryMode;
97
98    use crate::blob::DiffLineStats;
99
100    /// The source of a rewrite, rename or copy.
101    #[derive(Debug, Clone, PartialEq, PartialOrd)]
102    pub struct Source<'a, T> {
103        /// The kind of entry.
104        pub entry_mode: EntryMode,
105        /// The hash of the state of the source as seen in the object database.
106        pub id: gix_hash::ObjectId,
107        /// Further specify what kind of source this is.
108        pub kind: SourceKind,
109        /// The repository-relative location of this entry.
110        pub location: &'a BStr,
111        /// The change that was registered as source.
112        pub change: &'a T,
113        /// If this is a rewrite, indicate how many lines would need to change to turn this source into the destination.
114        pub diff: Option<DiffLineStats>,
115    }
116
117    /// Further identify the kind of [Source].
118    #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
119    pub enum SourceKind {
120        /// This is the source of an entry that was renamed, as `source` was renamed to `destination`.
121        Rename,
122        /// This is the source of a copy, as `source` was copied into `destination`.
123        Copy,
124    }
125
126    /// A change along with a location.
127    #[derive(Debug, Clone)]
128    pub struct Destination<'a, T: Clone> {
129        /// The change at the given `location`.
130        pub change: T,
131        /// The repository-relative location of this destination.
132        pub location: &'a BStr,
133    }
134}
135
136///
137pub mod emit {
138    /// The error returned by [Tracker::emit()](super::Tracker::emit()).
139    #[derive(Debug, thiserror::Error)]
140    #[expect(missing_docs)]
141    pub enum Error {
142        #[error("Could not find blob for similarity checking")]
143        FindExistingBlob(#[from] gix_object::find::existing_object::Error),
144        #[error("Could not obtain exhaustive item set to use as possible sources for copy detection")]
145        GetItemsForExhaustiveCopyDetection(#[source] Box<dyn std::error::Error + Send + Sync>),
146        #[error(transparent)]
147        SetResource(#[from] crate::blob::platform::set_resource::Error),
148        #[error(transparent)]
149        PrepareDiff(#[from] crate::blob::platform::prepare_diff::Error),
150    }
151}
152
153/// Lifecycle
154impl<T: Change> Tracker<T> {
155    /// Create a new instance with `rewrites` configuration.
156    pub fn new(rewrites: Rewrites) -> Self {
157        Tracker {
158            items: vec![],
159            path_backing: vec![],
160            rewrites,
161            child_renames: Default::default(),
162        }
163    }
164}
165
166/// build state and find matches.
167impl<T: Change> Tracker<T> {
168    /// We may refuse the push if that information isn't needed for what we have to track.
169    pub fn try_push_change(&mut self, change: T, location: &BStr) -> Option<T> {
170        let change_kind = change.kind();
171        if let (None, ChangeKind::Modification) = (self.rewrites.copies, change_kind) {
172            return Some(change);
173        }
174
175        let entry_kind = change.entry_mode().kind();
176        if entry_kind == EntryKind::Commit {
177            return Some(change);
178        }
179        let relation = change
180            .relation()
181            .filter(|_| matches!(change_kind, ChangeKind::Addition | ChangeKind::Deletion));
182        if let (None, EntryKind::Tree) = (relation, entry_kind) {
183            return Some(change);
184        }
185
186        let start = self.path_backing.len();
187        self.path_backing.extend_from_slice(location);
188        let path = start..self.path_backing.len();
189
190        self.items.push(Item {
191            path,
192            change,
193            emitted: false,
194        });
195        None
196    }
197
198    /// Can only be called once effectively as it alters its own state to assure each item is only emitted once.
199    ///
200    /// `cb(destination, source)` is called for each item, either with `Some(source)` if it's
201    /// the destination of a copy or rename, or with `None` for source if no relation to other
202    /// items in the tracked set exist, which is like saying 'no rename or rewrite or copy' happened.
203    /// Note that directories with [relation](Relation) will be emitted if there is a match, along with all their matching
204    /// child-items which are similarly bundled as rename.
205    ///
206    /// `objects` is used to access blob data for similarity checks if required and is taken directly from the object database.
207    /// Worktree filters and text conversions will be applied afterwards automatically. Note that object-caching *should not*
208    /// be enabled as caching is implemented by `diff_cache`, after all, the blob that's actually diffed is going
209    /// through conversion steps.
210    ///
211    /// `diff_cache` is a way to retain a cache of resources that are prepared for rapid diffing, and it also controls
212    /// the diff-algorithm (provided no user-algorithm is set).
213    /// Note that we control a few options of `diff_cache` to assure it will ignore external commands.
214    /// Note that we do not control how the `diff_cache` converts resources, it's left to the caller to decide
215    /// if it should look at what's stored in `git`, or in the working tree, along with all diff-specific conversions.
216    ///
217    /// `push_source_tree(push_fn: push(change, location))` is a function that is called when the entire tree of the source
218    /// should be added as modifications by calling `push` repeatedly to use for perfect copy tracking. Note that `push`
219    /// will panic if `change` is not a modification, and it's valid to not call `push` at all.
220    pub fn emit<PushSourceTreeFn, E>(
221        &mut self,
222        mut cb: impl FnMut(visit::Destination<'_, T>, Option<visit::Source<'_, T>>) -> Action,
223        diff_cache: &mut crate::blob::Platform,
224        objects: &impl gix_object::FindObjectOrHeader,
225        mut push_source_tree: PushSourceTreeFn,
226    ) -> Result<Outcome, emit::Error>
227    where
228        PushSourceTreeFn: FnMut(&mut dyn FnMut(T, &BStr)) -> Result<(), E>,
229        E: std::error::Error + Send + Sync + 'static,
230    {
231        fn is_parent(change: &impl Change) -> bool {
232            matches!(change.relation(), Some(Relation::Parent(_)))
233        }
234        diff_cache.options.skip_internal_diff_if_external_is_configured = false;
235
236        // Early abort: if there is no pair, don't do anything.
237        let has_work = {
238            let (mut num_deletions, mut num_additions, mut num_modifications) = (0, 0, 0);
239            let mut has_work = false;
240            for change in &self.items {
241                match change.change.kind() {
242                    ChangeKind::Deletion => {
243                        num_deletions += 1;
244                    }
245                    ChangeKind::Modification => {
246                        // This means we have copy-tracking enabled
247                        num_modifications += 1;
248                    }
249                    ChangeKind::Addition => num_additions += 1,
250                }
251                if (num_deletions != 0 && num_additions != 0)
252                    || (self.rewrites.copies.is_some() && num_modifications + num_additions > 1)
253                {
254                    has_work = true;
255                    break;
256                }
257            }
258            has_work
259        };
260
261        let mut out = Outcome {
262            options: self.rewrites,
263            ..Default::default()
264        };
265        if has_work {
266            self.sort_items_by_id_and_location();
267
268            // Rewrites by directory (without local changes) can be pruned out quickly,
269            // by finding only parents, their counterpart, and then all children can be matched by
270            // relationship ID.
271            self.match_pairs_of_kind(
272                visit::SourceKind::Rename,
273                &mut cb,
274                None, /* by identity for parents */
275                &mut out,
276                diff_cache,
277                objects,
278                Some(is_parent),
279            )?;
280
281            self.match_pairs_of_kind(
282                visit::SourceKind::Rename,
283                &mut cb,
284                self.rewrites.percentage,
285                &mut out,
286                diff_cache,
287                objects,
288                None,
289            )?;
290
291            self.match_renamed_directories(&mut cb)?;
292
293            if let Some(copies) = self.rewrites.copies {
294                self.match_pairs_of_kind(
295                    visit::SourceKind::Copy,
296                    &mut cb,
297                    copies.percentage,
298                    &mut out,
299                    diff_cache,
300                    objects,
301                    None,
302                )?;
303
304                match copies.source {
305                    CopySource::FromSetOfModifiedFiles => {}
306                    CopySource::FromSetOfModifiedFilesAndAllSources => {
307                        push_source_tree(&mut |change, location| {
308                            if self.try_push_change(change, location).is_none() {
309                                // make sure these aren't viable to be emitted anymore.
310                                self.items.last_mut().expect("just pushed").emitted = true;
311                            }
312                        })
313                        .map_err(|err| emit::Error::GetItemsForExhaustiveCopyDetection(Box::new(err)))?;
314                        self.sort_items_by_id_and_location();
315
316                        self.match_pairs_of_kind(
317                            visit::SourceKind::Copy,
318                            &mut cb,
319                            copies.percentage,
320                            &mut out,
321                            diff_cache,
322                            objects,
323                            None,
324                        )?;
325                    }
326                }
327            }
328        }
329
330        self.items
331            .sort_by(|a, b| a.location(&self.path_backing).cmp(b.location(&self.path_backing)));
332        for item in self.items.drain(..).filter(|item| !item.emitted) {
333            if cb(
334                visit::Destination {
335                    location: item.location(&self.path_backing),
336                    change: item.change,
337                },
338                None,
339            )
340            .is_break()
341            {
342                break;
343            }
344        }
345        Ok(out)
346    }
347}
348
349impl<T: Change> Tracker<T> {
350    /// Sort `items` primarily by their id, so identity-based lookups can be found quickly by
351    /// partitioning (see `find_match`). Same-id items are then ordered by location, change-kind,
352    /// relation and entry-mode - a total order over each item's observable identity - so that
353    /// matching is deterministic and independent of the order in which changes were pushed, which
354    /// the parallel dirwalk and index-traversal threads leave nondeterministic
355    /// (see <https://github.com/GitoxideLabs/gitoxide/issues/1832>). Any items that still compare
356    /// equal are identical in every observable field and are thus interchangeable for matching.
357    fn sort_items_by_id_and_location(&mut self) {
358        self.items.sort_by(|a, b| {
359            a.change
360                .id()
361                .cmp(b.change.id())
362                .then_with(|| a.location(&self.path_backing).cmp(b.location(&self.path_backing)))
363                .then_with(|| a.change.kind().cmp(&b.change.kind()))
364                .then_with(|| a.change.relation().cmp(&b.change.relation()))
365                .then_with(|| a.change.entry_mode().cmp(&b.change.entry_mode()))
366        });
367    }
368
369    #[expect(clippy::too_many_arguments)]
370    fn match_pairs_of_kind(
371        &mut self,
372        kind: visit::SourceKind,
373        cb: &mut impl FnMut(visit::Destination<'_, T>, Option<visit::Source<'_, T>>) -> Action,
374        percentage: Option<f32>,
375        out: &mut Outcome,
376        diff_cache: &mut crate::blob::Platform,
377        objects: &impl gix_object::FindObjectOrHeader,
378        filter: Option<fn(&T) -> bool>,
379    ) -> Result<(), emit::Error> {
380        // we try to cheaply reduce the set of possibilities first, before possibly looking more exhaustively.
381        let needs_second_pass = !needs_exact_match(percentage);
382
383        // https://github.com/git/git/blob/cc01bad4a9f566cf4453c7edd6b433851b0835e2/diffcore-rename.c#L350-L369
384        // We would need a hashmap to be OK to not use the limit here, otherwise the performance is too bad.
385        // This also means we don't find all renames if we hit the rename limit.
386        if self
387            .match_pairs(cb, None /* by identity */, kind, out, diff_cache, objects, filter)?
388            .is_break()
389        {
390            return Ok(());
391        }
392        if needs_second_pass {
393            let is_limited = if self.rewrites.limit == 0 {
394                false
395            } else {
396                let (num_src, num_dst) =
397                    estimate_involved_items(self.items.iter().map(|item| (item.emitted, item.change.kind())), kind);
398                let permutations = num_src * num_dst;
399                if permutations > self.rewrites.limit {
400                    match kind {
401                        visit::SourceKind::Rename => {
402                            out.num_similarity_checks_skipped_for_rename_tracking_due_to_limit = permutations;
403                        }
404                        visit::SourceKind::Copy => {
405                            out.num_similarity_checks_skipped_for_copy_tracking_due_to_limit = permutations;
406                        }
407                    }
408                    true
409                } else {
410                    false
411                }
412            };
413            if !is_limited {
414                let _ = self.match_pairs(cb, percentage, kind, out, diff_cache, objects, None)?;
415            }
416        }
417        Ok(())
418    }
419
420    #[expect(clippy::too_many_arguments)]
421    fn match_pairs(
422        &mut self,
423        cb: &mut impl FnMut(visit::Destination<'_, T>, Option<visit::Source<'_, T>>) -> Action,
424        percentage: Option<f32>,
425        kind: visit::SourceKind,
426        stats: &mut Outcome,
427        diff_cache: &mut crate::blob::Platform,
428        objects: &impl gix_object::FindObjectOrHeader,
429        filter: Option<fn(&T) -> bool>,
430    ) -> Result<Action, emit::Error> {
431        let mut dest_ofs = 0;
432        let mut num_checks = 0;
433        let max_checks = {
434            let limit = self.rewrites.limit.saturating_pow(2);
435            // There can be trees with a lot of entries and pathological search behaviour, as they can be repeated
436            // and then have a lot of similar hashes. This also means we have to search a lot of candidates which
437            // can be too slow despite best attempts. So play it save and detect such cases 'roughly' by amount of items.
438            if self.items.len() < 100_000 { 0 } else { limit }
439        };
440
441        while let Some((mut dest_idx, dest)) = self.items[dest_ofs..].iter().enumerate().find_map(|(idx, item)| {
442            (!item.emitted
443                && matches!(item.change.kind(), ChangeKind::Addition)
444                && filter.map_or_else(
445                    || {
446                        self.rewrites.track_empty
447                            // We always want to keep track of entries that are involved of a directory rename.
448                            // Note that this may still match them up arbitrarily if empty, but empty is empty.
449                            || matches!(item.change.relation(), Some(Relation::ChildOfParent(_)))
450                            || {
451                                let id = item.change.id();
452                                id != gix_hash::ObjectId::empty_blob(id.kind())
453                            }
454                    },
455                    |f| f(&item.change),
456                ))
457            .then_some((idx, item))
458        }) {
459            dest_idx += dest_ofs;
460            dest_ofs = dest_idx + 1;
461            self.items[dest_idx].location(&self.path_backing);
462            let src = find_match(
463                &self.items,
464                dest,
465                dest_idx,
466                percentage,
467                kind,
468                stats,
469                objects,
470                diff_cache,
471                &self.path_backing,
472                &mut num_checks,
473            )?
474            .map(|(src_idx, src, diff)| {
475                let (id, entry_mode) = src.change.id_and_entry_mode();
476                let id = id.to_owned();
477                let location = src.location(&self.path_backing);
478                (
479                    visit::Source {
480                        entry_mode,
481                        id,
482                        kind,
483                        location,
484                        change: &src.change,
485                        diff,
486                    },
487                    src_idx,
488                )
489            });
490            if max_checks != 0 && num_checks > max_checks {
491                gix_trace::warn!(
492                    "Cancelled rename matching as there were too many iterations ({num_checks} > {max_checks})"
493                );
494                return Ok(std::ops::ControlFlow::Break(()));
495            }
496            let Some((src, src_idx)) = src else {
497                continue;
498            };
499            let location = dest.location(&self.path_backing);
500            let change = dest.change.clone();
501            let dest = visit::Destination { change, location };
502            let relations = if percentage.is_none() {
503                src.change.relation().zip(dest.change.relation())
504            } else {
505                None
506            };
507            let res = cb(dest, Some(src));
508
509            self.items[dest_idx].emitted = true;
510            self.items[src_idx].emitted = true;
511
512            if res.is_break() {
513                return Ok(std::ops::ControlFlow::Break(()));
514            }
515
516            match relations {
517                Some((Relation::Parent(src), Relation::Parent(dst))) => {
518                    let res = self.emit_child_renames_matching_identity(cb, kind, src, dst)?;
519                    if res.is_break() {
520                        return Ok(std::ops::ControlFlow::Break(()));
521                    }
522                }
523                Some((Relation::ChildOfParent(src), Relation::ChildOfParent(dst))) => {
524                    self.child_renames.insert((src, dst));
525                }
526                _ => {}
527            }
528        }
529        Ok(std::ops::ControlFlow::Continue(()))
530    }
531
532    /// Emit the children of `src_parent_id` and `dst_parent_id` as pairs of exact matches, which are assumed
533    /// as `src` and `dst` were an exact match (so all children have to match exactly).
534    /// Note that we intentionally do not record them as their parents will be emitted, too.
535    fn emit_child_renames_matching_identity(
536        &mut self,
537        cb: &mut impl FnMut(visit::Destination<'_, T>, Option<visit::Source<'_, T>>) -> Action,
538        kind: visit::SourceKind,
539        src_parent_id: ChangeId,
540        dst_parent_id: ChangeId,
541    ) -> Result<Action, emit::Error> {
542        debug_assert_ne!(
543            src_parent_id, dst_parent_id,
544            "src and destination directories must be distinct"
545        );
546        let (mut src_items, mut dst_items) = (Vec::with_capacity(1), Vec::with_capacity(1));
547        for item in self.items.iter_mut().filter(|item| !item.emitted) {
548            match item.change.relation() {
549                Some(Relation::ChildOfParent(id)) if id == src_parent_id => {
550                    src_items.push((item.change.id().to_owned(), item));
551                }
552                Some(Relation::ChildOfParent(id)) if id == dst_parent_id => {
553                    dst_items.push((item.change.id().to_owned(), item));
554                }
555                _ => continue,
556            }
557        }
558
559        for ((src_id, src_item), (dst_id, dst_item)) in src_items.into_iter().zip(dst_items) {
560            // Since the parent items are already identical by ID, we know that the children will also match, we just
561            // double-check to still have a chance to be correct in case some of that goes wrong.
562            if src_id == dst_id
563                && filename(src_item.location(&self.path_backing)) == filename(dst_item.location(&self.path_backing))
564            {
565                let entry_mode = src_item.change.entry_mode();
566                let location = src_item.location(&self.path_backing);
567                let src = visit::Source {
568                    entry_mode,
569                    id: src_id,
570                    kind,
571                    location,
572                    change: &src_item.change,
573                    diff: None,
574                };
575                let location = dst_item.location(&self.path_backing);
576                let change = dst_item.change.clone();
577                let dst = visit::Destination { change, location };
578                let res = cb(dst, Some(src));
579
580                src_item.emitted = true;
581                dst_item.emitted = true;
582
583                if res.is_break() {
584                    return Ok(res);
585                }
586            } else {
587                gix_trace::warn!(
588                    "Children of parents with change-id {src_parent_id} and {dst_parent_id} were not equal, even though their parents claimed to be"
589                );
590                break;
591            }
592        }
593        Ok(std::ops::ControlFlow::Continue(()))
594    }
595
596    /// Find directories with relation id that haven't been emitted yet and store them for lookup.
597    /// Then use the previously stored emitted renames with relation id to learn which directories they 'link'
598    /// and emit them, too.
599    /// Note that this works whenever top-level directories are renamed because they are always added and deleted,
600    /// and we only match those. Thus, one rewrite inside the directory is enough.
601    fn match_renamed_directories(
602        &mut self,
603        cb: &mut impl FnMut(visit::Destination<'_, T>, Option<visit::Source<'_, T>>) -> Action,
604    ) -> Result<(), emit::Error> {
605        fn unemitted_directory_matching_relation_id<T: Change>(items: &[Item<T>], child_id: ChangeId) -> Option<usize> {
606            items.iter().position(|i| {
607                !i.emitted && matches!(i.change.relation(), Some(Relation::Parent(pid)) if pid == child_id)
608            })
609        }
610        for (deleted_child_id, added_child_id) in &self.child_renames {
611            let Some(src_idx) = unemitted_directory_matching_relation_id(&self.items, *deleted_child_id) else {
612                continue;
613            };
614            let Some(dst_idx) = unemitted_directory_matching_relation_id(&self.items, *added_child_id) else {
615                // This could go wrong in case there are mismatches, so be defensive here.
616                // But generally, we'd expect the destination item to exist.
617                continue;
618            };
619
620            let (src_item, dst_item) = (&self.items[src_idx], &self.items[dst_idx]);
621            let entry_mode = src_item.change.entry_mode();
622            let location = src_item.location(&self.path_backing);
623            let src = visit::Source {
624                entry_mode,
625                id: src_item.change.id().to_owned(),
626                kind: SourceKind::Rename,
627                location,
628                change: &src_item.change,
629                diff: None,
630            };
631            let location = dst_item.location(&self.path_backing);
632            let change = dst_item.change.clone();
633            let dst = visit::Destination { change, location };
634            let res = cb(dst, Some(src));
635
636            self.items[src_idx].emitted = true;
637            self.items[dst_idx].emitted = true;
638
639            if res.is_break() {
640                return Ok(());
641            }
642        }
643        Ok(())
644    }
645}
646
647fn filename(path: &BStr) -> &BStr {
648    path.rfind_byte(b'/').map_or(path, |idx| path[idx + 1..].as_bstr())
649}
650
651/// Returns the amount of viable sources and destinations for `items` as eligible for the given `kind` of operation.
652fn estimate_involved_items(
653    items: impl IntoIterator<Item = (bool, ChangeKind)>,
654    kind: visit::SourceKind,
655) -> (usize, usize) {
656    items
657        .into_iter()
658        .filter(|(emitted, _)| match kind {
659            visit::SourceKind::Rename => !*emitted,
660            visit::SourceKind::Copy => true,
661        })
662        .fold((0, 0), |(mut src, mut dest), (emitted, change_kind)| {
663            match change_kind {
664                ChangeKind::Addition => {
665                    if kind == visit::SourceKind::Rename || !emitted {
666                        dest += 1;
667                    }
668                }
669                ChangeKind::Deletion => {
670                    if kind == visit::SourceKind::Rename {
671                        src += 1;
672                    }
673                }
674                ChangeKind::Modification => {
675                    if kind == visit::SourceKind::Copy {
676                        src += 1;
677                    }
678                }
679            }
680            (src, dest)
681        })
682}
683
684fn needs_exact_match(percentage: Option<f32>) -> bool {
685    percentage.is_none_or(|p| p >= 1.0)
686}
687
688/// <`src_idx`, src, possibly diff stat>
689type SourceTuple<'a, T> = (usize, &'a Item<T>, Option<DiffLineStats>);
690
691/// Find `item` in our set of items ignoring `item_idx` to avoid finding ourselves, by similarity indicated by `percentage`.
692/// The latter can be `None` or `Some(x)` where `x>=1` for identity, and anything else for similarity.
693/// We also ignore emitted items entirely.
694/// Use `kind` to indicate what kind of match we are looking for, which might be deletions matching an `item` addition, or
695/// any non-deletion otherwise.
696/// Note that we always try to find by identity first even if a percentage is given as it's much faster and may reduce the set
697/// of items to be searched.
698#[expect(clippy::too_many_arguments)]
699fn find_match<'a, T: Change>(
700    items: &'a [Item<T>],
701    item: &Item<T>,
702    item_idx: usize,
703    percentage: Option<f32>,
704    kind: visit::SourceKind,
705    stats: &mut Outcome,
706    objects: &impl gix_object::FindObjectOrHeader,
707    diff_cache: &mut crate::blob::Platform,
708    path_backing: &[u8],
709    num_checks: &mut usize,
710) -> Result<Option<SourceTuple<'a, T>>, emit::Error> {
711    let (item_id, item_mode) = item.change.id_and_entry_mode();
712    if needs_exact_match(percentage) || item_mode.is_link() {
713        let first_idx = items.partition_point(|a| a.change.id() < item_id);
714        let range = items.get(first_idx..).map(|slice| {
715            let end = slice
716                .iter()
717                .position(|a| a.change.id() != item_id)
718                .map_or(items.len(), |idx| first_idx + idx);
719            first_idx..end
720        });
721        let range = match range {
722            Some(range) => range,
723            None => return Ok(None),
724        };
725        if range.is_empty() {
726            return Ok(None);
727        }
728        let item_name = filename(item.location(path_backing));
729        let mut fallback = None;
730        for (mut src_idx, src) in items[range.clone()].iter().enumerate() {
731            src_idx += range.start;
732            *num_checks += 1;
733            if src_idx == item_idx || !src.is_source_for_destination_of(kind, item_mode) {
734                continue;
735            }
736            // Like Git, prefer a source whose file name matches the destination's to keep
737            // renames of equally-named files together when contents are identical.
738            if filename(src.location(path_backing)) == item_name {
739                return Ok(Some((src_idx, src, None)));
740            }
741            fallback.get_or_insert((src_idx, src, None));
742        }
743        if fallback.is_some() {
744            return Ok(fallback);
745        }
746    } else if item_mode.is_blob() {
747        let mut has_new = false;
748        let percentage = percentage.expect("it's set to something below 1.0 and we assured this");
749        let item_name = filename(item.location(path_backing));
750
751        // Like Git's inexact rename matrix, choose by similarity score first and use basename as
752        // a tie-breaker only.
753        let mut best: Option<(usize, &Item<T>, DiffLineStats, bool)> = None;
754        for (can_idx, src) in items
755            .iter()
756            .enumerate()
757            .filter(|(src_idx, src)| *src_idx != item_idx && src.is_source_for_destination_of(kind, item_mode))
758        {
759            if !has_new {
760                diff_cache.set_resource(
761                    item_id.to_owned(),
762                    item_mode.kind(),
763                    item.location(path_backing),
764                    ResourceKind::NewOrDestination,
765                    objects,
766                )?;
767                has_new = true;
768            }
769            let (src_id, src_mode) = src.change.id_and_entry_mode();
770            diff_cache.set_resource(
771                src_id.to_owned(),
772                src_mode.kind(),
773                src.location(path_backing),
774                ResourceKind::OldOrSource,
775                objects,
776            )?;
777            let prep = diff_cache.prepare_diff()?;
778            stats.num_similarity_checks += 1;
779            *num_checks += 1;
780            match prep.operation {
781                Operation::InternalDiff { algorithm } => {
782                    let tokens = crate::blob::InternedInput::new(prep.old.intern_source(), prep.new.intern_source());
783                    let diff = crate::blob::Diff::compute(algorithm, &tokens);
784                    let removed_bytes = diff::removed_bytes(&diff, &tokens);
785                    let old_data_len = prep.old.data.as_slice().unwrap_or_default().len();
786                    let new_data_len = prep.new.data.as_slice().unwrap_or_default().len();
787                    let similarity = (old_data_len - removed_bytes) as f32 / old_data_len.max(new_data_len) as f32;
788                    if similarity >= percentage {
789                        let candidate_diff = DiffLineStats {
790                            removals: diff.count_removals(),
791                            insertions: diff.count_additions(),
792                            before: tokens.before.len(),
793                            after: tokens.after.len(),
794                            similarity,
795                        };
796                        let has_same_filename = filename(src.location(path_backing)) == item_name;
797                        let is_better =
798                            best.as_ref()
799                                .is_none_or(|(_, _, best_diff, best_has_same_filename)| {
800                                    match candidate_diff.similarity.total_cmp(&best_diff.similarity) {
801                                        std::cmp::Ordering::Greater => true,
802                                        std::cmp::Ordering::Equal => has_same_filename && !best_has_same_filename,
803                                        std::cmp::Ordering::Less => false,
804                                    }
805                                });
806                        if is_better {
807                            best = Some((can_idx, src, candidate_diff, has_same_filename));
808                        }
809                    }
810                }
811                Operation::ExternalCommand { .. } => {
812                    unreachable!("we have disabled this possibility with an option")
813                }
814                Operation::SourceOrDestinationIsBinary => {
815                    // TODO: figure out if git does more here
816                }
817            }
818        }
819        return Ok(best.map(|(candidate_idx, src, diff, _)| (candidate_idx, src, Some(diff))));
820    }
821    Ok(None)
822}
823
824mod diff {
825    pub fn removed_bytes(diff: &crate::blob::Diff, input: &crate::blob::InternedInput<&[u8]>) -> usize {
826        diff.hunks()
827            .map(|hunk| {
828                input.before[hunk.before.start as usize..hunk.before.end as usize]
829                    .iter()
830                    .map(|token| input.interner[*token].len())
831                    .sum::<usize>()
832            })
833            .sum()
834    }
835}
836
837#[cfg(test)]
838mod estimate_involved_items {
839    use super::estimate_involved_items;
840    use crate::rewrites::tracker::{ChangeKind, visit::SourceKind};
841
842    #[test]
843    fn renames_count_unemitted_as_sources_and_destinations() {
844        let items = [
845            (false, ChangeKind::Addition),
846            (true, ChangeKind::Deletion),
847            (true, ChangeKind::Deletion),
848        ];
849        assert_eq!(
850            estimate_involved_items(items, SourceKind::Rename),
851            (0, 1),
852            "here we only have one eligible source, hence nothing to do"
853        );
854        assert_eq!(
855            estimate_involved_items(items.into_iter().map(|t| (false, t.1)), SourceKind::Rename),
856            (2, 1),
857            "now we have more possibilities as renames count un-emitted deletions as source"
858        );
859    }
860
861    #[test]
862    fn copies_do_not_count_additions_as_sources() {
863        let items = [
864            (false, ChangeKind::Addition),
865            (true, ChangeKind::Addition),
866            (true, ChangeKind::Deletion),
867        ];
868        assert_eq!(
869            estimate_involved_items(items, SourceKind::Copy),
870            (0, 1),
871            "one addition as source, the other isn't counted as it's emitted, nor is it considered a copy-source.\
872            deletions don't count"
873        );
874    }
875
876    #[test]
877    fn copies_count_modifications_as_sources() {
878        let items = [
879            (false, ChangeKind::Addition),
880            (true, ChangeKind::Modification),
881            (false, ChangeKind::Modification),
882        ];
883        assert_eq!(
884            estimate_involved_items(items, SourceKind::Copy),
885            (2, 1),
886            "any modifications is a valid source, emitted or not"
887        );
888    }
889}