3 * Copyright (C) 2005 Junio C Hamano
8 #include "object-store.h"
11 #include "promisor-remote.h"
13 /* Table of rename/copy destinations */
15 static struct diff_rename_dst {
16 struct diff_filespec *two;
17 struct diff_filepair *pair;
19 static int rename_dst_nr, rename_dst_alloc;
21 static int find_rename_dst(struct diff_filespec *two)
27 while (last > first) {
28 int next = first + ((last - first) >> 1);
29 struct diff_rename_dst *dst = &(rename_dst[next]);
30 int cmp = strcmp(two->path, dst->two->path);
42 static struct diff_rename_dst *locate_rename_dst(struct diff_filespec *two)
44 int ofs = find_rename_dst(two);
45 return ofs < 0 ? NULL : &rename_dst[ofs];
49 * Returns 0 on success, -1 if we found a duplicate.
51 static int add_rename_dst(struct diff_filespec *two)
53 int first = find_rename_dst(two);
59 /* insert to make it at "first" */
60 ALLOC_GROW(rename_dst, rename_dst_nr + 1, rename_dst_alloc);
62 if (first < rename_dst_nr)
63 MOVE_ARRAY(rename_dst + first + 1, rename_dst + first,
64 rename_dst_nr - first - 1);
65 rename_dst[first].two = alloc_filespec(two->path);
66 fill_filespec(rename_dst[first].two, &two->oid, two->oid_valid,
68 rename_dst[first].pair = NULL;
72 /* Table of rename/copy src files */
73 static struct diff_rename_src {
74 struct diff_filepair *p;
75 unsigned short score; /* to remember the break score */
77 static int rename_src_nr, rename_src_alloc;
79 static void register_rename_src(struct diff_filepair *p)
82 * If we have multiple entries at the same path in the source tree
83 * (an invalid tree, to be sure), avoid using more more than one
84 * such entry in rename detection. Once upon a time, doing so
85 * caused segfaults; see commit 25d5ea410f ("[PATCH] Redo
86 * rename/copy detection logic.", 2005-05-24).
88 if (rename_src_nr > 0 &&
89 !strcmp(rename_src[rename_src_nr-1].p->one->path, p->one->path))
92 ALLOC_GROW(rename_src, rename_src_nr + 1, rename_src_alloc);
93 rename_src[rename_src_nr].p = p;
94 rename_src[rename_src_nr].score = p->score;
98 static int basename_same(struct diff_filespec *src, struct diff_filespec *dst)
100 int src_len = strlen(src->path), dst_len = strlen(dst->path);
101 while (src_len && dst_len) {
102 char c1 = src->path[--src_len];
103 char c2 = dst->path[--dst_len];
109 return (!src_len || src->path[src_len - 1] == '/') &&
110 (!dst_len || dst->path[dst_len - 1] == '/');
114 int src; /* index in rename_src */
115 int dst; /* index in rename_dst */
116 unsigned short score;
120 struct prefetch_options {
121 struct repository *repo;
124 static void prefetch(void *prefetch_options)
126 struct prefetch_options *options = prefetch_options;
128 struct oid_array to_fetch = OID_ARRAY_INIT;
130 for (i = 0; i < rename_dst_nr; i++) {
131 if (rename_dst[i].pair)
133 * The loop in diffcore_rename() will not need these
134 * blobs, so skip prefetching.
136 continue; /* already found exact match */
137 diff_add_if_missing(options->repo, &to_fetch,
140 for (i = 0; i < rename_src_nr; i++) {
141 if (options->skip_unmodified &&
142 diff_unmodified_pair(rename_src[i].p))
144 * The loop in diffcore_rename() will not need these
145 * blobs, so skip prefetching.
148 diff_add_if_missing(options->repo, &to_fetch,
149 rename_src[i].p->one);
151 promisor_remote_get_direct(options->repo, to_fetch.oid, to_fetch.nr);
152 oid_array_clear(&to_fetch);
155 static int estimate_similarity(struct repository *r,
156 struct diff_filespec *src,
157 struct diff_filespec *dst,
161 /* src points at a file that existed in the original tree (or
162 * optionally a file in the destination tree) and dst points
163 * at a newly created file. They may be quite similar, in which
164 * case we want to say src is renamed to dst or src is copied into
165 * dst, and then some edit has been applied to dst.
167 * Compare them and return how similar they are, representing
168 * the score as an integer between 0 and MAX_SCORE.
170 * When there is an exact match, it is considered a better
171 * match than anything else; the destination does not even
172 * call into this function in that case.
174 unsigned long max_size, delta_size, base_size, src_copied, literal_added;
176 struct diff_populate_filespec_options dpf_options = {
179 struct prefetch_options prefetch_options = {r, skip_unmodified};
181 if (r == the_repository && has_promisor_remote()) {
182 dpf_options.missing_object_cb = prefetch;
183 dpf_options.missing_object_data = &prefetch_options;
186 /* We deal only with regular files. Symlink renames are handled
187 * only when they are exact matches --- in other words, no edits
190 if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
194 * Need to check that source and destination sizes are
195 * filled in before comparing them.
197 * If we already have "cnt_data" filled in, we know it's
198 * all good (avoid checking the size for zero, as that
199 * is a possible size - we really should have a flag to
200 * say whether the size is valid or not!)
202 if (!src->cnt_data &&
203 diff_populate_filespec(r, src, &dpf_options))
205 if (!dst->cnt_data &&
206 diff_populate_filespec(r, dst, &dpf_options))
209 max_size = ((src->size > dst->size) ? src->size : dst->size);
210 base_size = ((src->size < dst->size) ? src->size : dst->size);
211 delta_size = max_size - base_size;
213 /* We would not consider edits that change the file size so
214 * drastically. delta_size must be smaller than
215 * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
217 * Note that base_size == 0 case is handled here already
218 * and the final score computation below would not have a
219 * divide-by-zero issue.
221 if (max_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
224 dpf_options.check_size_only = 0;
226 if (!src->cnt_data && diff_populate_filespec(r, src, &dpf_options))
228 if (!dst->cnt_data && diff_populate_filespec(r, dst, &dpf_options))
231 if (diffcore_count_changes(r, src, dst,
232 &src->cnt_data, &dst->cnt_data,
233 &src_copied, &literal_added))
236 /* How similar are they?
237 * what percentage of material in dst are from source?
240 score = 0; /* should not happen */
242 score = (int)(src_copied * MAX_SCORE / max_size);
246 static void record_rename_pair(int dst_index, int src_index, int score)
248 struct diff_filespec *src, *dst;
249 struct diff_filepair *dp;
251 if (rename_dst[dst_index].pair)
252 die("internal error: dst already matched.");
254 src = rename_src[src_index].p->one;
258 dst = rename_dst[dst_index].two;
261 dp = diff_queue(NULL, src, dst);
262 dp->renamed_pair = 1;
263 if (!strcmp(src->path, dst->path))
264 dp->score = rename_src[src_index].score;
267 rename_dst[dst_index].pair = dp;
271 * We sort the rename similarity matrix with the score, in descending
272 * order (the most similar first).
274 static int score_compare(const void *a_, const void *b_)
276 const struct diff_score *a = a_, *b = b_;
278 /* sink the unused ones to the bottom */
280 return (0 <= b->dst);
284 if (a->score == b->score)
285 return b->name_score - a->name_score;
287 return b->score - a->score;
290 struct file_similarity {
291 struct hashmap_entry entry;
293 struct diff_filespec *filespec;
296 static unsigned int hash_filespec(struct repository *r,
297 struct diff_filespec *filespec)
299 if (!filespec->oid_valid) {
300 if (diff_populate_filespec(r, filespec, NULL))
302 hash_object_file(r->hash_algo, filespec->data, filespec->size,
303 "blob", &filespec->oid);
305 return oidhash(&filespec->oid);
308 static int find_identical_files(struct hashmap *srcs,
310 struct diff_options *options)
313 struct diff_filespec *target = rename_dst[dst_index].two;
314 struct file_similarity *p, *best = NULL;
315 int i = 100, best_score = -1;
316 unsigned int hash = hash_filespec(options->repo, target);
319 * Find the best source match for specified destination.
321 p = hashmap_get_entry_from_hash(srcs, hash, NULL,
322 struct file_similarity, entry);
323 hashmap_for_each_entry_from(srcs, p, entry) {
325 struct diff_filespec *source = p->filespec;
327 /* False hash collision? */
328 if (!oideq(&source->oid, &target->oid))
330 /* Non-regular files? If so, the modes must match! */
331 if (!S_ISREG(source->mode) || !S_ISREG(target->mode)) {
332 if (source->mode != target->mode)
335 /* Give higher scores to sources that haven't been used already */
336 score = !source->rename_used;
337 if (source->rename_used && options->detect_rename != DIFF_DETECT_COPY)
339 score += basename_same(source, target);
340 if (score > best_score) {
347 /* Too many identical alternatives? Pick one */
352 record_rename_pair(dst_index, best->index, MAX_SCORE);
358 static void insert_file_table(struct repository *r,
359 struct hashmap *table, int index,
360 struct diff_filespec *filespec)
362 struct file_similarity *entry = xmalloc(sizeof(*entry));
364 entry->index = index;
365 entry->filespec = filespec;
367 hashmap_entry_init(&entry->entry, hash_filespec(r, filespec));
368 hashmap_add(table, &entry->entry);
372 * Find exact renames first.
374 * The first round matches up the up-to-date entries,
375 * and then during the second round we try to match
376 * cache-dirty entries as well.
378 static int find_exact_renames(struct diff_options *options)
381 struct hashmap file_table;
383 /* Add all sources to the hash table in reverse order, because
384 * later on they will be retrieved in LIFO order.
386 hashmap_init(&file_table, NULL, NULL, rename_src_nr);
387 for (i = rename_src_nr-1; i >= 0; i--)
388 insert_file_table(options->repo,
390 rename_src[i].p->one);
392 /* Walk the destinations and find best source match */
393 for (i = 0; i < rename_dst_nr; i++)
394 renames += find_identical_files(&file_table, i, options);
396 /* Free the hash data structure and entries */
397 hashmap_clear_and_free(&file_table, struct file_similarity, entry);
402 #define NUM_CANDIDATE_PER_DST 4
403 static void record_if_better(struct diff_score m[], struct diff_score *o)
407 /* find the worst one */
409 for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
410 if (score_compare(&m[i], &m[worst]) > 0)
413 /* is it better than the worst one? */
414 if (score_compare(&m[worst], o) > 0)
420 * 0 if we are under the limit;
421 * 1 if we need to disable inexact rename detection;
422 * 2 if we would be under the limit if we were given -C instead of -C -C.
424 static int too_many_rename_candidates(int num_destinations, int num_sources,
425 struct diff_options *options)
427 int rename_limit = options->rename_limit;
428 int i, limited_sources;
430 options->needed_rename_limit = 0;
433 * This basically does a test for the rename matrix not
434 * growing larger than a "rename_limit" square matrix, ie:
436 * num_destinations * num_sources > rename_limit * rename_limit
438 * We use st_mult() to check overflow conditions; in the
439 * exceptional circumstance that size_t isn't large enough to hold
440 * the multiplication, the system won't be able to allocate enough
441 * memory for the matrix anyway.
443 if (rename_limit <= 0)
444 rename_limit = 32767;
445 if (st_mult(num_destinations, num_sources)
446 <= st_mult(rename_limit, rename_limit))
449 options->needed_rename_limit =
450 num_sources > num_destinations ? num_sources : num_destinations;
452 /* Are we running under -C -C? */
453 if (!options->flags.find_copies_harder)
456 /* Would we bust the limit if we were running under -C? */
457 for (limited_sources = i = 0; i < num_sources; i++) {
458 if (diff_unmodified_pair(rename_src[i].p))
462 if (st_mult(num_destinations, limited_sources)
463 <= st_mult(rename_limit, rename_limit))
468 static int find_renames(struct diff_score *mx, int dst_cnt, int minimum_score, int copies)
472 for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
473 struct diff_rename_dst *dst;
475 if ((mx[i].dst < 0) ||
476 (mx[i].score < minimum_score))
477 break; /* there is no more usable pair. */
478 dst = &rename_dst[mx[i].dst];
480 continue; /* already done, either exact or fuzzy. */
481 if (!copies && rename_src[mx[i].src].p->one->rename_used)
483 record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
489 void diffcore_rename(struct diff_options *options)
491 int detect_rename = options->detect_rename;
492 int minimum_score = options->rename_score;
493 struct diff_queue_struct *q = &diff_queued_diff;
494 struct diff_queue_struct outq;
495 struct diff_score *mx;
496 int i, j, rename_count, skip_unmodified = 0;
497 int num_destinations, dst_cnt;
498 struct progress *progress = NULL;
501 minimum_score = DEFAULT_RENAME_SCORE;
503 for (i = 0; i < q->nr; i++) {
504 struct diff_filepair *p = q->queue[i];
505 if (!DIFF_FILE_VALID(p->one)) {
506 if (!DIFF_FILE_VALID(p->two))
507 continue; /* unmerged */
508 else if (options->single_follow &&
509 strcmp(options->single_follow, p->two->path))
510 continue; /* not interested */
511 else if (!options->flags.rename_empty &&
512 is_empty_blob_oid(&p->two->oid))
514 else if (add_rename_dst(p->two) < 0) {
515 warning("skipping rename detection, detected"
516 " duplicate destination '%s'",
521 else if (!options->flags.rename_empty &&
522 is_empty_blob_oid(&p->one->oid))
524 else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
526 * If the source is a broken "delete", and
527 * they did not really want to get broken,
528 * that means the source actually stays.
529 * So we increment the "rename_used" score
530 * by one, to indicate ourselves as a user
532 if (p->broken_pair && !p->score)
533 p->one->rename_used++;
534 register_rename_src(p);
536 else if (detect_rename == DIFF_DETECT_COPY) {
538 * Increment the "rename_used" score by
539 * one, to indicate ourselves as a user.
541 p->one->rename_used++;
542 register_rename_src(p);
545 if (rename_dst_nr == 0 || rename_src_nr == 0)
546 goto cleanup; /* nothing to do */
549 * We really want to cull the candidates list early
550 * with cheap tests in order to avoid doing deltas.
552 rename_count = find_exact_renames(options);
554 /* Did we only want exact renames? */
555 if (minimum_score == MAX_SCORE)
559 * Calculate how many renames are left (but all the source
560 * files still remain as options for rename/copies!)
562 num_destinations = (rename_dst_nr - rename_count);
565 if (!num_destinations)
568 switch (too_many_rename_candidates(num_destinations, rename_src_nr,
573 options->degraded_cc_to_c = 1;
580 if (options->show_rename_progress) {
581 progress = start_delayed_progress(
582 _("Performing inexact rename detection"),
583 (uint64_t)num_destinations * (uint64_t)rename_src_nr);
586 mx = xcalloc(st_mult(NUM_CANDIDATE_PER_DST, num_destinations),
588 for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
589 struct diff_filespec *two = rename_dst[i].two;
590 struct diff_score *m;
592 if (rename_dst[i].pair)
593 continue; /* dealt with exact match already. */
595 m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
596 for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
599 for (j = 0; j < rename_src_nr; j++) {
600 struct diff_filespec *one = rename_src[j].p->one;
601 struct diff_score this_src;
603 if (skip_unmodified &&
604 diff_unmodified_pair(rename_src[j].p))
607 this_src.score = estimate_similarity(options->repo,
611 this_src.name_score = basename_same(one, two);
614 record_if_better(m, &this_src);
616 * Once we run estimate_similarity,
617 * We do not need the text anymore.
619 diff_free_filespec_blob(one);
620 diff_free_filespec_blob(two);
623 display_progress(progress,
624 (uint64_t)dst_cnt * (uint64_t)rename_src_nr);
626 stop_progress(&progress);
628 /* cost matrix sorted by most to least similar pair */
629 STABLE_QSORT(mx, dst_cnt * NUM_CANDIDATE_PER_DST, score_compare);
631 rename_count += find_renames(mx, dst_cnt, minimum_score, 0);
632 if (detect_rename == DIFF_DETECT_COPY)
633 rename_count += find_renames(mx, dst_cnt, minimum_score, 1);
637 /* At this point, we have found some renames and copies and they
638 * are recorded in rename_dst. The original list is still in *q.
640 DIFF_QUEUE_CLEAR(&outq);
641 for (i = 0; i < q->nr; i++) {
642 struct diff_filepair *p = q->queue[i];
643 struct diff_filepair *pair_to_free = NULL;
645 if (DIFF_PAIR_UNMERGED(p)) {
648 else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
652 * We would output this create record if it has
653 * not been turned into a rename/copy already.
655 struct diff_rename_dst *dst = locate_rename_dst(p->two);
656 if (dst && dst->pair) {
657 diff_q(&outq, dst->pair);
661 /* no matching rename/copy source, so
662 * record this as a creation.
666 else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
670 * We would output this delete record if:
672 * (1) this is a broken delete and the counterpart
673 * broken create remains in the output; or
674 * (2) this is not a broken delete, and rename_dst
675 * does not have a rename/copy to move p->one->path
678 * Otherwise, the counterpart broken create
679 * has been turned into a rename-edit; or
680 * delete did not have a matching create to
683 if (DIFF_PAIR_BROKEN(p)) {
685 struct diff_rename_dst *dst = locate_rename_dst(p->one);
686 if (dst && dst->pair)
687 /* counterpart is now rename/copy */
691 if (p->one->rename_used)
692 /* this path remains */
701 else if (!diff_unmodified_pair(p))
702 /* all the usual ones need to be kept */
705 /* no need to keep unmodified pairs */
709 diff_free_filepair(pair_to_free);
711 diff_debug_queue("done copying original", &outq);
715 diff_debug_queue("done collapsing", q);
717 for (i = 0; i < rename_dst_nr; i++)
718 free_filespec(rename_dst[i].two);
720 FREE_AND_NULL(rename_dst);
721 rename_dst_nr = rename_dst_alloc = 0;
722 FREE_AND_NULL(rename_src);
723 rename_src_nr = rename_src_alloc = 0;