1use std::cmp::Ordering;
2use std::cmp::Reverse;
3use std::collections::{BTreeMap, HashMap};
4
5use codeint_model::{RepoPath, StableHasher};
6
7use crate::{GitError, Snapshot};
8
9#[cfg(test)]
10mod tests;
11
12pub const DEFAULT_RENAME_THRESHOLD: u8 = 50;
13pub const MAX_RENAME_THRESHOLD: u8 = 100;
14
15const DEFAULT_RENAME_LIMIT: usize = 1000;
16const BINARY_CHECK_BYTES: usize = 8000;
17const MAX_CHUNK_BYTES: usize = 64;
18
19#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct RenameMap {
21 old_to_new: BTreeMap<RepoPath, RepoPath>,
22 new_to_old: BTreeMap<RepoPath, RepoPath>,
23}
24
25impl RenameMap {
26 pub fn is_empty(&self) -> bool {
27 self.old_to_new.is_empty()
28 }
29
30 pub fn len(&self) -> usize {
31 self.old_to_new.len()
32 }
33
34 pub fn new_path_for(&self, old_path: &RepoPath) -> Option<&RepoPath> {
35 self.old_to_new.get(old_path)
36 }
37
38 pub fn old_path_for(&self, new_path: &RepoPath) -> Option<&RepoPath> {
39 self.new_to_old.get(new_path)
40 }
41
42 pub fn is_renamed_destination(&self, path: &RepoPath) -> bool {
43 self.new_to_old.contains_key(path)
44 }
45
46 pub fn is_renamed_source(&self, path: &RepoPath) -> bool {
47 self.old_to_new.contains_key(path)
48 }
49
50 pub fn iter(&self) -> impl Iterator<Item = (&RepoPath, &RepoPath)> {
51 self.old_to_new.iter()
52 }
53
54 pub fn as_string_map(&self) -> BTreeMap<String, String> {
55 self.old_to_new
56 .iter()
57 .map(|(old_path, new_path)| (old_path.to_string(), new_path.to_string()))
58 .collect()
59 }
60
61 fn insert(&mut self, old_path: RepoPath, new_path: RepoPath) {
62 self.new_to_old.insert(new_path.clone(), old_path.clone());
63 self.old_to_new.insert(old_path, new_path);
64 }
65}
66
67impl Snapshot {
68 pub fn detect_renames_from(
69 &self,
70 base: &Snapshot,
71 threshold: u8,
72 ) -> Result<RenameMap, GitError> {
73 if threshold == 0 || threshold > MAX_RENAME_THRESHOLD {
74 return Ok(RenameMap::default());
75 }
76 let (deleted_paths, added_paths) = deleted_and_added(base.files(), self.files());
77 if deleted_paths.is_empty() || added_paths.is_empty() {
78 return Ok(RenameMap::default());
79 }
80 let deleted = load_non_empty_blobs(base, &deleted_paths)?;
81 let added = load_non_empty_blobs(self, &added_paths)?;
82 Ok(match_renamed_blobs(&deleted, &added, threshold))
83 }
84}
85
86fn match_renamed_blobs(
87 deleted: &[FileBlob<'_>],
88 added: &[FileBlob<'_>],
89 threshold: u8,
90) -> RenameMap {
91 let mut renames = RenameMap::default();
92 if deleted.is_empty() || added.is_empty() {
93 return renames;
94 }
95 let (unmatched_deleted, unmatched_added) = pair_exact_matches(deleted, added, &mut renames);
96 if threshold < MAX_RENAME_THRESHOLD
97 && !unmatched_deleted.is_empty()
98 && !unmatched_added.is_empty()
99 {
100 pair_similar_matches(
101 deleted,
102 added,
103 &unmatched_deleted,
104 &unmatched_added,
105 threshold,
106 &mut renames,
107 );
108 }
109 renames
110}
111
112struct FileBlob<'a> {
113 path: &'a RepoPath,
114 bytes: Vec<u8>,
115 hash: u64,
116}
117
118struct ChunkProfile {
119 len: usize,
120 chunks: HashMap<u64, usize>,
121}
122
123fn deleted_and_added<'a>(
124 base_files: &'a [RepoPath],
125 head_files: &'a [RepoPath],
126) -> (Vec<&'a RepoPath>, Vec<&'a RepoPath>) {
127 let mut deleted = Vec::new();
128 let mut added = Vec::new();
129 let mut base_index = 0;
130 let mut head_index = 0;
131 while base_index < base_files.len() && head_index < head_files.len() {
132 match base_files[base_index].cmp(&head_files[head_index]) {
133 Ordering::Less => {
134 deleted.push(&base_files[base_index]);
135 base_index += 1;
136 }
137 Ordering::Greater => {
138 added.push(&head_files[head_index]);
139 head_index += 1;
140 }
141 Ordering::Equal => {
142 base_index += 1;
143 head_index += 1;
144 }
145 }
146 }
147 deleted.extend(&base_files[base_index..]);
148 added.extend(&head_files[head_index..]);
149 (deleted, added)
150}
151
152fn load_non_empty_blobs<'a>(
153 snapshot: &Snapshot,
154 paths: &[&'a RepoPath],
155) -> Result<Vec<FileBlob<'a>>, GitError> {
156 let reader = snapshot.parallel_reader().thread_local();
157 let mut blobs = Vec::with_capacity(paths.len());
158 for &path in paths {
159 let bytes = match reader.read(path) {
160 Ok(bytes) => bytes,
161 Err(GitError::ReadBlob { .. }) => continue,
162 Err(error) => return Err(error),
163 };
164 if bytes.is_empty() {
165 continue;
166 }
167 let hash = StableHasher::new()
168 .write_u64(bytes.len() as u64)
169 .write_bytes(&bytes)
170 .finish();
171 blobs.push(FileBlob { path, bytes, hash });
172 }
173 Ok(blobs)
174}
175
176fn pair_exact_matches(
177 deleted: &[FileBlob<'_>],
178 added: &[FileBlob<'_>],
179 renames: &mut RenameMap,
180) -> (Vec<usize>, Vec<usize>) {
181 let mut added_by_hash: HashMap<u64, Vec<usize>> = HashMap::new();
182 for (index, blob) in added.iter().enumerate() {
183 added_by_hash.entry(blob.hash).or_default().push(index);
184 }
185 let mut deleted_used = vec![false; deleted.len()];
186 let mut added_used = vec![false; added.len()];
187
188 for pass_same_basename in [true, false] {
189 for (del_index, del_blob) in deleted.iter().enumerate() {
190 if deleted_used[del_index] {
191 continue;
192 }
193 let Some(candidates) = added_by_hash.get(&del_blob.hash) else {
194 continue;
195 };
196 let matched = candidates.iter().copied().find(|&add_index| {
197 !added_used[add_index]
198 && (!pass_same_basename
199 || basename(del_blob.path) == basename(added[add_index].path))
200 && del_blob.bytes == added[add_index].bytes
201 });
202 if let Some(add_index) = matched {
203 deleted_used[del_index] = true;
204 added_used[add_index] = true;
205 renames.insert(del_blob.path.clone(), added[add_index].path.clone());
206 }
207 }
208 }
209
210 let unmatched_deleted = deleted_used
211 .iter()
212 .enumerate()
213 .filter_map(|(index, &used)| (!used).then_some(index))
214 .collect();
215 let unmatched_added = added_used
216 .iter()
217 .enumerate()
218 .filter_map(|(index, &used)| (!used).then_some(index))
219 .collect();
220 (unmatched_deleted, unmatched_added)
221}
222
223fn pair_similar_matches(
224 deleted: &[FileBlob<'_>],
225 added: &[FileBlob<'_>],
226 unmatched_deleted: &[usize],
227 unmatched_added: &[usize],
228 threshold: u8,
229 renames: &mut RenameMap,
230) {
231 if unmatched_deleted
232 .len()
233 .saturating_mul(unmatched_added.len())
234 > DEFAULT_RENAME_LIMIT * DEFAULT_RENAME_LIMIT
235 {
236 return;
237 }
238 let del_profiles = build_text_profiles(deleted, unmatched_deleted);
239 let add_profiles = build_text_profiles(added, unmatched_added);
240 if del_profiles.is_empty() || add_profiles.is_empty() {
241 return;
242 }
243 let mut candidates =
244 collect_similar_candidates(deleted, added, &del_profiles, &add_profiles, threshold);
245 sort_similar_candidates(
246 &mut candidates,
247 deleted,
248 added,
249 &del_profiles,
250 &add_profiles,
251 );
252 select_greedy_renames(
253 &candidates,
254 deleted,
255 added,
256 &del_profiles,
257 &add_profiles,
258 renames,
259 );
260}
261
262fn collect_similar_candidates(
263 deleted: &[FileBlob<'_>],
264 added: &[FileBlob<'_>],
265 del_profiles: &[(usize, ChunkProfile)],
266 add_profiles: &[(usize, ChunkProfile)],
267 threshold: u8,
268) -> Vec<(u8, bool, usize, usize)> {
269 let mut candidates = Vec::new();
270 for (del_pos, &(del_index, ref del_profile)) in del_profiles.iter().enumerate() {
271 for (add_pos, &(add_index, ref add_profile)) in add_profiles.iter().enumerate() {
272 if !lengths_can_reach_threshold(del_profile.len, add_profile.len, threshold) {
273 continue;
274 }
275 let score = similarity_percent(del_profile, add_profile);
276 if score >= threshold {
277 let same_basename =
278 basename(deleted[del_index].path) == basename(added[add_index].path);
279 candidates.push((score, same_basename, del_pos, add_pos));
280 }
281 }
282 }
283 candidates
284}
285
286fn sort_similar_candidates(
287 candidates: &mut [(u8, bool, usize, usize)],
288 deleted: &[FileBlob<'_>],
289 added: &[FileBlob<'_>],
290 del_profiles: &[(usize, ChunkProfile)],
291 add_profiles: &[(usize, ChunkProfile)],
292) {
293 candidates.sort_by(|left, right| {
294 Reverse(left.0)
295 .cmp(&Reverse(right.0))
296 .then_with(|| Reverse(left.1).cmp(&Reverse(right.1)))
297 .then_with(|| {
298 deleted[del_profiles[left.2].0]
299 .path
300 .cmp(deleted[del_profiles[right.2].0].path)
301 })
302 .then_with(|| {
303 added[add_profiles[left.3].0]
304 .path
305 .cmp(added[add_profiles[right.3].0].path)
306 })
307 });
308}
309
310fn select_greedy_renames(
311 candidates: &[(u8, bool, usize, usize)],
312 deleted: &[FileBlob<'_>],
313 added: &[FileBlob<'_>],
314 del_profiles: &[(usize, ChunkProfile)],
315 add_profiles: &[(usize, ChunkProfile)],
316 renames: &mut RenameMap,
317) {
318 let mut del_used = vec![false; del_profiles.len()];
319 let mut add_used = vec![false; add_profiles.len()];
320 for &(_, _, del_pos, add_pos) in candidates {
321 if del_used[del_pos] || add_used[add_pos] {
322 continue;
323 }
324 del_used[del_pos] = true;
325 add_used[add_pos] = true;
326 let old_path = deleted[del_profiles[del_pos].0].path.clone();
327 let new_path = added[add_profiles[add_pos].0].path.clone();
328 renames.insert(old_path, new_path);
329 }
330}
331
332fn build_text_profiles(blobs: &[FileBlob<'_>], indices: &[usize]) -> Vec<(usize, ChunkProfile)> {
333 indices
334 .iter()
335 .copied()
336 .filter(|&index| !is_binary(&blobs[index].bytes))
337 .map(|index| (index, chunk_profile(&blobs[index].bytes)))
338 .collect()
339}
340
341fn lengths_can_reach_threshold(left_len: usize, right_len: usize, threshold: u8) -> bool {
342 let min_len = left_len.min(right_len) as u128;
343 let max_len = left_len.max(right_len) as u128;
344 max_len > 0 && min_len * 100 >= max_len * u128::from(threshold)
345}
346
347fn chunk_profile(bytes: &[u8]) -> ChunkProfile {
348 let mut chunks = HashMap::new();
349 let mut start = 0;
350 while start < bytes.len() {
351 let mut end = start;
352 while end < bytes.len() && end - start < MAX_CHUNK_BYTES {
353 let byte = bytes[end];
354 end += 1;
355 if byte == b'\n' {
356 break;
357 }
358 }
359 let slice = &bytes[start..end];
360 let hash = StableHasher::new().write_bytes(slice).finish();
361 *chunks.entry(hash).or_insert(0) += slice.len();
362 start = end;
363 }
364 ChunkProfile {
365 len: bytes.len(),
366 chunks,
367 }
368}
369
370fn similarity_percent(left: &ChunkProfile, right: &ChunkProfile) -> u8 {
371 let (smaller, larger) = if left.chunks.len() <= right.chunks.len() {
372 (&left.chunks, &right.chunks)
373 } else {
374 (&right.chunks, &left.chunks)
375 };
376 let mut matched_bytes: usize = 0;
377 for (hash, &left_bytes) in smaller {
378 if let Some(&right_bytes) = larger.get(hash) {
379 matched_bytes += left_bytes.min(right_bytes);
380 }
381 }
382 let max_len = left.len.max(right.len) as u128;
383 if max_len == 0 {
384 return 0;
385 }
386 ((matched_bytes as u128 * 100) / max_len).min(100) as u8
387}
388
389fn is_binary(bytes: &[u8]) -> bool {
390 bytes.iter().take(BINARY_CHECK_BYTES).any(|&byte| byte == 0)
391}
392
393fn basename(path: &RepoPath) -> &str {
394 path.as_str().rsplit('/').next().unwrap_or(path.as_str())
395}