use std::cmp::Ordering;
use std::cmp::Reverse;
use std::collections::{BTreeMap, HashMap};
use codeint_model::{RepoPath, StableHasher};
use crate::{GitError, Snapshot};
#[cfg(test)]
mod tests;
pub const DEFAULT_RENAME_THRESHOLD: u8 = 50;
pub const MAX_RENAME_THRESHOLD: u8 = 100;
const DEFAULT_RENAME_LIMIT: usize = 1000;
const BINARY_CHECK_BYTES: usize = 8000;
const MAX_CHUNK_BYTES: usize = 64;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RenameMap {
old_to_new: BTreeMap<RepoPath, RepoPath>,
new_to_old: BTreeMap<RepoPath, RepoPath>,
}
impl RenameMap {
pub fn is_empty(&self) -> bool {
self.old_to_new.is_empty()
}
pub fn len(&self) -> usize {
self.old_to_new.len()
}
pub fn new_path_for(&self, old_path: &RepoPath) -> Option<&RepoPath> {
self.old_to_new.get(old_path)
}
pub fn old_path_for(&self, new_path: &RepoPath) -> Option<&RepoPath> {
self.new_to_old.get(new_path)
}
pub fn is_renamed_destination(&self, path: &RepoPath) -> bool {
self.new_to_old.contains_key(path)
}
pub fn is_renamed_source(&self, path: &RepoPath) -> bool {
self.old_to_new.contains_key(path)
}
pub fn iter(&self) -> impl Iterator<Item = (&RepoPath, &RepoPath)> {
self.old_to_new.iter()
}
pub fn as_string_map(&self) -> BTreeMap<String, String> {
self.old_to_new
.iter()
.map(|(old_path, new_path)| (old_path.to_string(), new_path.to_string()))
.collect()
}
fn insert(&mut self, old_path: RepoPath, new_path: RepoPath) {
self.new_to_old.insert(new_path.clone(), old_path.clone());
self.old_to_new.insert(old_path, new_path);
}
}
impl Snapshot {
pub fn detect_renames_from(
&self,
base: &Snapshot,
threshold: u8,
) -> Result<RenameMap, GitError> {
if threshold == 0 || threshold > MAX_RENAME_THRESHOLD {
return Ok(RenameMap::default());
}
let (deleted_paths, added_paths) = deleted_and_added(base.files(), self.files());
if deleted_paths.is_empty() || added_paths.is_empty() {
return Ok(RenameMap::default());
}
let deleted = load_non_empty_blobs(base, &deleted_paths)?;
let added = load_non_empty_blobs(self, &added_paths)?;
Ok(match_renamed_blobs(&deleted, &added, threshold))
}
}
fn match_renamed_blobs(
deleted: &[FileBlob<'_>],
added: &[FileBlob<'_>],
threshold: u8,
) -> RenameMap {
let mut renames = RenameMap::default();
if deleted.is_empty() || added.is_empty() {
return renames;
}
let (unmatched_deleted, unmatched_added) = pair_exact_matches(deleted, added, &mut renames);
if threshold < MAX_RENAME_THRESHOLD
&& !unmatched_deleted.is_empty()
&& !unmatched_added.is_empty()
{
pair_similar_matches(
deleted,
added,
&unmatched_deleted,
&unmatched_added,
threshold,
&mut renames,
);
}
renames
}
struct FileBlob<'a> {
path: &'a RepoPath,
bytes: Vec<u8>,
hash: u64,
}
struct ChunkProfile {
len: usize,
chunks: HashMap<u64, usize>,
}
fn deleted_and_added<'a>(
base_files: &'a [RepoPath],
head_files: &'a [RepoPath],
) -> (Vec<&'a RepoPath>, Vec<&'a RepoPath>) {
let mut deleted = Vec::new();
let mut added = Vec::new();
let mut base_index = 0;
let mut head_index = 0;
while base_index < base_files.len() && head_index < head_files.len() {
match base_files[base_index].cmp(&head_files[head_index]) {
Ordering::Less => {
deleted.push(&base_files[base_index]);
base_index += 1;
}
Ordering::Greater => {
added.push(&head_files[head_index]);
head_index += 1;
}
Ordering::Equal => {
base_index += 1;
head_index += 1;
}
}
}
deleted.extend(&base_files[base_index..]);
added.extend(&head_files[head_index..]);
(deleted, added)
}
fn load_non_empty_blobs<'a>(
snapshot: &Snapshot,
paths: &[&'a RepoPath],
) -> Result<Vec<FileBlob<'a>>, GitError> {
let reader = snapshot.parallel_reader().thread_local();
let mut blobs = Vec::with_capacity(paths.len());
for &path in paths {
let bytes = match reader.read(path) {
Ok(bytes) => bytes,
Err(GitError::ReadBlob { .. }) => continue,
Err(error) => return Err(error),
};
if bytes.is_empty() {
continue;
}
let hash = StableHasher::new()
.write_u64(bytes.len() as u64)
.write_bytes(&bytes)
.finish();
blobs.push(FileBlob { path, bytes, hash });
}
Ok(blobs)
}
fn pair_exact_matches(
deleted: &[FileBlob<'_>],
added: &[FileBlob<'_>],
renames: &mut RenameMap,
) -> (Vec<usize>, Vec<usize>) {
let mut added_by_hash: HashMap<u64, Vec<usize>> = HashMap::new();
for (index, blob) in added.iter().enumerate() {
added_by_hash.entry(blob.hash).or_default().push(index);
}
let mut deleted_used = vec![false; deleted.len()];
let mut added_used = vec![false; added.len()];
for pass_same_basename in [true, false] {
for (del_index, del_blob) in deleted.iter().enumerate() {
if deleted_used[del_index] {
continue;
}
let Some(candidates) = added_by_hash.get(&del_blob.hash) else {
continue;
};
let matched = candidates.iter().copied().find(|&add_index| {
!added_used[add_index]
&& (!pass_same_basename
|| basename(del_blob.path) == basename(added[add_index].path))
&& del_blob.bytes == added[add_index].bytes
});
if let Some(add_index) = matched {
deleted_used[del_index] = true;
added_used[add_index] = true;
renames.insert(del_blob.path.clone(), added[add_index].path.clone());
}
}
}
let unmatched_deleted = deleted_used
.iter()
.enumerate()
.filter_map(|(index, &used)| (!used).then_some(index))
.collect();
let unmatched_added = added_used
.iter()
.enumerate()
.filter_map(|(index, &used)| (!used).then_some(index))
.collect();
(unmatched_deleted, unmatched_added)
}
fn pair_similar_matches(
deleted: &[FileBlob<'_>],
added: &[FileBlob<'_>],
unmatched_deleted: &[usize],
unmatched_added: &[usize],
threshold: u8,
renames: &mut RenameMap,
) {
if unmatched_deleted
.len()
.saturating_mul(unmatched_added.len())
> DEFAULT_RENAME_LIMIT * DEFAULT_RENAME_LIMIT
{
return;
}
let del_profiles = build_text_profiles(deleted, unmatched_deleted);
let add_profiles = build_text_profiles(added, unmatched_added);
if del_profiles.is_empty() || add_profiles.is_empty() {
return;
}
let mut candidates =
collect_similar_candidates(deleted, added, &del_profiles, &add_profiles, threshold);
sort_similar_candidates(
&mut candidates,
deleted,
added,
&del_profiles,
&add_profiles,
);
select_greedy_renames(
&candidates,
deleted,
added,
&del_profiles,
&add_profiles,
renames,
);
}
fn collect_similar_candidates(
deleted: &[FileBlob<'_>],
added: &[FileBlob<'_>],
del_profiles: &[(usize, ChunkProfile)],
add_profiles: &[(usize, ChunkProfile)],
threshold: u8,
) -> Vec<(u8, bool, usize, usize)> {
let mut candidates = Vec::new();
for (del_pos, &(del_index, ref del_profile)) in del_profiles.iter().enumerate() {
for (add_pos, &(add_index, ref add_profile)) in add_profiles.iter().enumerate() {
if !lengths_can_reach_threshold(del_profile.len, add_profile.len, threshold) {
continue;
}
let score = similarity_percent(del_profile, add_profile);
if score >= threshold {
let same_basename =
basename(deleted[del_index].path) == basename(added[add_index].path);
candidates.push((score, same_basename, del_pos, add_pos));
}
}
}
candidates
}
fn sort_similar_candidates(
candidates: &mut [(u8, bool, usize, usize)],
deleted: &[FileBlob<'_>],
added: &[FileBlob<'_>],
del_profiles: &[(usize, ChunkProfile)],
add_profiles: &[(usize, ChunkProfile)],
) {
candidates.sort_by(|left, right| {
Reverse(left.0)
.cmp(&Reverse(right.0))
.then_with(|| Reverse(left.1).cmp(&Reverse(right.1)))
.then_with(|| {
deleted[del_profiles[left.2].0]
.path
.cmp(deleted[del_profiles[right.2].0].path)
})
.then_with(|| {
added[add_profiles[left.3].0]
.path
.cmp(added[add_profiles[right.3].0].path)
})
});
}
fn select_greedy_renames(
candidates: &[(u8, bool, usize, usize)],
deleted: &[FileBlob<'_>],
added: &[FileBlob<'_>],
del_profiles: &[(usize, ChunkProfile)],
add_profiles: &[(usize, ChunkProfile)],
renames: &mut RenameMap,
) {
let mut del_used = vec![false; del_profiles.len()];
let mut add_used = vec![false; add_profiles.len()];
for &(_, _, del_pos, add_pos) in candidates {
if del_used[del_pos] || add_used[add_pos] {
continue;
}
del_used[del_pos] = true;
add_used[add_pos] = true;
let old_path = deleted[del_profiles[del_pos].0].path.clone();
let new_path = added[add_profiles[add_pos].0].path.clone();
renames.insert(old_path, new_path);
}
}
fn build_text_profiles(blobs: &[FileBlob<'_>], indices: &[usize]) -> Vec<(usize, ChunkProfile)> {
indices
.iter()
.copied()
.filter(|&index| !is_binary(&blobs[index].bytes))
.map(|index| (index, chunk_profile(&blobs[index].bytes)))
.collect()
}
fn lengths_can_reach_threshold(left_len: usize, right_len: usize, threshold: u8) -> bool {
let min_len = left_len.min(right_len) as u128;
let max_len = left_len.max(right_len) as u128;
max_len > 0 && min_len * 100 >= max_len * u128::from(threshold)
}
fn chunk_profile(bytes: &[u8]) -> ChunkProfile {
let mut chunks = HashMap::new();
let mut start = 0;
while start < bytes.len() {
let mut end = start;
while end < bytes.len() && end - start < MAX_CHUNK_BYTES {
let byte = bytes[end];
end += 1;
if byte == b'\n' {
break;
}
}
let slice = &bytes[start..end];
let hash = StableHasher::new().write_bytes(slice).finish();
*chunks.entry(hash).or_insert(0) += slice.len();
start = end;
}
ChunkProfile {
len: bytes.len(),
chunks,
}
}
fn similarity_percent(left: &ChunkProfile, right: &ChunkProfile) -> u8 {
let (smaller, larger) = if left.chunks.len() <= right.chunks.len() {
(&left.chunks, &right.chunks)
} else {
(&right.chunks, &left.chunks)
};
let mut matched_bytes: usize = 0;
for (hash, &left_bytes) in smaller {
if let Some(&right_bytes) = larger.get(hash) {
matched_bytes += left_bytes.min(right_bytes);
}
}
let max_len = left.len.max(right.len) as u128;
if max_len == 0 {
return 0;
}
((matched_bytes as u128 * 100) / max_len).min(100) as u8
}
fn is_binary(bytes: &[u8]) -> bool {
bytes.iter().take(BINARY_CHECK_BYTES).any(|&byte| byte == 0)
}
fn basename(path: &RepoPath) -> &str {
path.as_str().rsplit('/').next().unwrap_or(path.as_str())
}